I have a String
which has a name of a class say "Ex"
(no .class
extension). I want to assign it to a Class
variable, like this:
Class cls = (string).class
How can i do that?
The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.
Get Object Type Using getClass() in Java We'll use the getClass() method of the Object class, the parent class of all objects in Java. We check the class using the if condition. As the wrapper classes also contain a field class that returns the type, we can check whose type matches with var1 and var2 .
Class<?> cls = Class.forName(className);
But your className
should be fully-qualified - i.e. com.mycompany.MyClass
String clsName = "Ex"; // use fully qualified name Class cls = Class.forName(clsName); Object clsInstance = (Object) cls.newInstance();
Check the Java Tutorial trail on Reflection at http://java.sun.com/docs/books/tutorial/reflect/TOC.html for further details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With