Bipin Wanchoo
Bipin Wanchoo

Reputation: 163

How to convert String type to Class type in java

I want to print all the class names in a package and also to print the corresponding attributes and their data types in each package.

In one code, I am able to get the classnames in the form of string. In another code I am able to get the attributes and their data types using Classname.class.getAttribute();

However I want to merge the two codes. Since in the first code I got the classnames in the form of string , I can't use Classname.class.getAttribute() since here Classname will be of type String.

So I want a method which will convert the "Classname" from String type to Class type.

I tried Class.forName() but it didn't work.

Upvotes: 15

Views: 61533

Answers (3)

Pranay
Pranay

Reputation: 11

Please try as following.

String str = "RequiredClassName";    
Class <?> Cref = Class .forName("PackageNaem."+str );

Upvotes: 1

heretolearn
heretolearn

Reputation: 6545

If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName().

Eg:

Class c = Class.forName("com.duke.MyLocaleServiceProvider"); 

Note: Make sure the parameter you provide for the function is fully qualified class name like com.package.class

Check here for any reference.

EDIT:

You could also try using loadClass() method.

Eg:

 ClassLoader cl;
 Class c = cl.loadClass(name);

It is invoked by the Java virtual machine to resolve class references.

Syntax:

public Class<?> loadClass(String name)
                   throws ClassNotFoundException

For details on ClassLoader check here

Here is an implementation of ClassLoader.

Upvotes: 1

Piyush Mattoo
Piyush Mattoo

Reputation: 16105

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

Make sure className is fully qualified class name like com.package.class Also, please share your error message that you see.

Upvotes: 27

Related Questions