Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Class type from String

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?

like image 595
Steven Avatar asked Mar 09 '10 12:03

Steven


People also ask

How do you return a class name from a String in Java?

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.

How do you find the class type of an object?

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 .


2 Answers

Class<?> cls = Class.forName(className); 

But your className should be fully-qualified - i.e. com.mycompany.MyClass

like image 52
Bozho Avatar answered Oct 12 '22 06:10

Bozho


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.

like image 38
JuanZe Avatar answered Oct 12 '22 05:10

JuanZe