Reputation: 15
I am just wondering if I can get an instance of a class (reference to an Object) during JVM runtime if I know its Classloader. Please refer to the code bellow to understand my question.
Class A:
package local.run;
public class A {
public static void main(String[] args) {
B b = new B();
b.setCount(5);
C c = new C();
c.dummyMethod();
b.printCount();
}
}
Class B:
package local.run;
public class B {
public int count = 0;
public void setCount(int aCount) {
count = aCount;
}
public void printCount() {
System.out.println(count);
}
}
Class C:
package local.run;
public class C {
public void dummyMethod() {
// Can I get the instance of class B created in class A here?
// I don't want to pass the instance of class B as a parameter to this method.
System.out.println("ClassLoader Namespace -> "+B.class.getProtectionDomain().getCodeSource().getLocation());
// I know the ClassLoader Namespace of class B
// How to get instance of class B created in class A???
System.out.println(b.count); // I wan't to print 5
}
}
If this is not prossible then I am just wondering how JSF implements @ManagedProperty feature?
Upvotes: 0
Views: 675
Reputation: 280132
No, you cannot get an instance of a give type from a ClassLoader
. How would the ClassLoader
be able to identify which instance you wanted?
You need some other kind of logic. Like Peter, I don't know how JSF does it exactly, so I'll give an example with Spring.
In Spring, which provides a Inversion of Control container, you declare your beans. These are managed by the container, ie. the container stores them and controls their entire life cycle. If you have a field within one of these beans' class declared as
@Value("${someBean.someField}")
private String copyValueOfThatField;
then the container is responsible for resolving the expression within the @Value
annotation and injecting the corresponding value into the copyValueOfThatField
field.
In this case, it will use some component that goes through all the beans registered in the container, find the one named someBean
, and try to retrieve the value of its someField
property.
You'll have tons of reflection going on in the background to get values of object fields.
JSF is a container in its own right and probably does something similar to the above. The use of the term Managed
should tell you that.
Upvotes: 2
Reputation: 533720
To get an instance, you have a to have a collection somewhere which retains the instance for lookup. I don't know how JSF work specifically, but usually your framework looks for special annotations it recognises and it holds the instances which are used to set those fields, or it has factories to create the instance.
Upvotes: 0