class ClassA {
private int a;
public void setA() {
a = 15;
System.out.println(a);
}
}
class ClassB extends ClassA {
public static void main( String[] args ) throws IllegalAccessException, InstantiationException {
Class cls = ClassB.class;
ClassB obj = (ClassB) cls.newInstance();
obj.setA(); //Accessible
obj.test(); // Accessible
}
public void test() {
setA();
}
}
It should be like this.
You want to instantiate a class by it's name?
First of all, you need to make a Class object:
Class cls = Class.forName(strClassName);
Then instantiate this (note, this can throw various exceptions - access violation, ClassNotFound, no public constructor without arguments etc.)
Object instance = cls.newInstance();
Then you can cast it:
return (SomeClass) instance;
Please make sure you understand the differences between:
A class name (approximately a file name)
A class object (essentially a type information)
A class instance (an actual object of this type)
You can also cast the cls object to have type Class, if you want. It doesn't give you much, though. And you can inline it, to:
return (SomeClass)(Class.forName(strClassName).newInstance());
Oh, but you can do type checking with the cls object, before instantiating it. So you only instanciate it, if it satisfies your API (implements the interface you want to get).
EDIT: add further example code, towards reflection.
For example:
if (cls.isInstance(request)) {
// ...
}