Java get reference to class

How to get the reference value of an object of a class in Java?

Goal of this program is to help me understand the concepts of Object creation and memory allocation in Java. Based on my understanding, the new operator shall create a memory for an object and return the reference stored in the memory. In order to get the address of the object, I am using the System.identityHashCode function. In order to get the value of the reference stored in that memory address, I am directly printing the object. Below we can see the results.

 The address of the mybox object is:1956725890 The value of the mybox object is:Box@74a14482 The address of the object mybox1 is :1956725890 The value of the mybox1 object is:Box@74a14482 The address of the object mybox2 is :356573597 The value of the mybox2 object is:Box@1540e19d 
  • Without instantiating, how would mybox1 have an address and a reference in that address ?
  • The book Java for complete reference does mention that every object after instantiation shall hold the memory address of the actual object Box.So why is the value of the reference stored in the mybox2 different from the value of the reference stored in mybox ? I am assuming that just by printing the variable, it would give me the value stored in that variable, which is the reference to the object Box.

Thank you people for any suggestions that can help me understand the very basic concepts of java. I am a newbie and I really appreciate the wealth of knowledge spread by stackoverflow members.

Источник

Get a reference of an object using class name Java

I’m Running a method annotated with @Test and I want get a reference to the object JunitCore , this object invokes the method by reflection. How can I get a reference to the that object, If It’s possible?(maybe a security issue) I tried reflection and classLoader but I couldn’t make it work. Thanks

Читайте также:  Exceeded 30 redirects python

Unless JUnit has a way to inject or give you a reference to the JunitCore , you cannot get it, even with reflection.

@Jon JunitCore seems to be the entry point of junit test cases. OP probably wants the instance that gets created in main .

I want to run testCases over ResultAnswer that is in the JunitCore object, to show my dynamic test cases in the eclipse plugin

2 Answers 2

The JUnitCore is a basic entry point for Junit tests. The way it works is it finds a List of classes provided as java command arguments and uses them to create a Runner with which it runs the test cases.

At no point during processing does the main method in JUnitCore ever pass a reference of the JUnitCore instance it creates to any other object. As such, it is not retrievable either directly or with reflection.

public static void main(String. args) < runMainAndExit(new RealSystem(), args); >public static void runMainAndExit(JUnitSystem system, String. args) < Result result= new JUnitCore().runMain(system, args); system.exit(result.wasSuccessful() ? 0 : 1); >public Result runMain(JUnitSystem system, String. args) < system.out().println("JUnit version " + Version.id()); List> classes= new ArrayList>(); List missingClasses= new ArrayList(); for (String each : args) try < classes.add(Class.forName(each)); >catch (ClassNotFoundException e) < system.out().println("Could not find class: " + each); Description description= Description.createSuiteDescription(each); Failure failure= new Failure(description, e); missingClasses.add(failure); >RunListener listener= new TextListener(system); addListener(listener); Result result= run(classes.toArray(new Class[0])); for (Failure each : missingClasses) result.getFailures().add(each); return result; > . // and more 

No where in this implementation is a reference to this passed as an argument. As such, you cannot get a reference to it.

Источник

Getting hold of the outer class object from the inner class object

I have the following code. I want to get hold of the outer class object using which I created the inner class object inner . How can I do it?

public class OuterClass < public class InnerClass < private String name = "Peakit"; >public static void main(String[] args) < OuterClass outer = new OuterClass(); InnerClass inner = outer.new InnerClass(); // How to get the same outer object which created the inner object back? OuterClass anotherOuter = ?? ; if(anotherOuter == outer) < System.out.println("Was able to reach out to the outer object via inner !!"); >else < System.out.println("No luck :-( "); >> > 

But what if I don’t have control to modify the inner class, then (just to confirm) do we have some other way of getting the corresponding outer class object from the inner class object?

Читайте также:  Соединение с postgresql java

7 Answers 7

Within the inner class itself, you can use OuterClass.this . This expression, which allows to refer to any lexically enclosing instance, is described in the JLS as Qualified this .

I don’t think there’s a way to get the instance from outside the code of the inner class though. Of course, you can always introduce your own property:

public OuterClass getOuter()

EDIT: By experimentation, it looks like the field holding the reference to the outer class has package level access — at least with the JDK I’m using.

EDIT: The name used ( this$0 ) is actually valid in Java, although the JLS discourages its use:

The $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

@peakit: Then as far as I know, you’re out of luck unless you use reflection. It feels like it’s a violation of encapsulation though really — if the inner class doesn’t want to tell you what its outer instance is, you should respect that and try to design such that you don’t need it.

OuterClass.this references the outer class.

You could (but you shouldn’t) use reflection for the job:

import java.lang.reflect.Field; public class Outer < public class Inner < >public static void main(String[] args) throws Exception < // Create the inner instance Inner inner = new Outer().new Inner(); // Get the implicit reference from the inner to the outer instance // . make it accessible, as it has default visibility Field field = Inner.class.getDeclaredField("this$0"); field.setAccessible(true); // Dereference and cast it Outer outer = (Outer) field.get(inner); System.out.println(outer); >> 

Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn’t 🙂

Читайте также:  Php запуск консольной команды

The more general answer to this question involves shadowed variables and how they are accessed.

In the following example (from Oracle), the variable x in main() is shadowing Test.x:

class Test < static int x = 1; public static void main(String[] args) < InnerClass innerClassInstance = new InnerClass() < public void printX() < System.out.print("x=" + x); System.out.println(", Test.this.x http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6" rel="nofollow noreferrer">http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Oct 17, 2017 at 19:30
answered Aug 12, 2016 at 20:00
1
    1
    Not sure that example proves the point best because "Test.this.x" is same as "Test.x" because it is static, doesn't really belong to the enclosing class object. I think would be better example if the code was in the constructor of class Test and Test.x not static.
    – sb4
    Jun 4, 2020 at 17:36
Add a comment|
0

Here's the example:

// Test public void foo() < C c = new C(); A s; s = ((A.B)c).get(); System.out.println(s.getR()); >// classes class C <> class A < public class B extends C< A get() > public String getR() < return "This is string"; >>

Источник

Оцените статью