Reputation: 700
i have class type saved in string like this:
String cls = "Test";
Here is some code i tried:
String cls = "Test";
Object obj = new Test();
Test test = (Class.forName(cls)) obj;
But it ends with compilation error:
Main.java:21: error: ';' expected
Test test = (Class.forName(cls)) obj;
How can I use this string for type conversion?
PS: Presume I don't know what type obj
is, I only have String cls
.
Upvotes: 0
Views: 105
Reputation: 1383
String cls = "Test";
Test t = new Test();
OtherTest ot = new OtherTest();
Class<?> c = Class.forName(cls);
if(t.getClass() == c) {
System.out.println("Hooray!");
}
if(ot.getClass() == c) {
System.out.println("Mmmmh");
}
It prints out "Hooray"
Is this what you want?
Upvotes: 0
Reputation: 662
You can use the cast method on the Class you created from the String:
String className = "Test";
Class<?> clz = Class.forName(className);
clz.cast(objectToBecasted);
Upvotes: 1
Reputation: 10652
If you want to instantiate a class for which you have the name, you were already on the right track:
// Remember that this class name tells us, it's in the default package,
// otherwise you would have to use the fully qualified name, for example
// com.mydomain.Test
String className = "Test";
// First we need to get the correct class object
Class<?> clz = Class.forName(className);
// And from this class object, we can create a new instance, in other
// words, a "Test" object:
Test test = (Test)clz.newInstance();
Of course, there are some exceptions that have to be caught (or declared), etc. But I think you get the idea. If you do not want to call the default constructor (the one with no arguments, in other words the equivalent of new Test()
) of your "Test" class, you would have to search the right constructors via the appropriate methods of the Class object (getDeclaredConstructor, etc.etc. - see the API doc for that).
Upvotes: 2
Reputation: 7730
java.lang.class.Class c=Class.forName("ClassNameToBeLoadedDynamically")
is not required as
A call to Class.forName("X") causes the class named X to be dynamically loaded (at runtime).
You can directly use
Test test = (Test) obj;
Upvotes: 0