How to convert String type to class type in java

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

In one code, I can get the class names as a string. In another code, I can get the attributes and their data types using Classname.class.getAttribute();

However, I want to combine the two codes. Since in the first code I got the class names as a string, I can not use Classname.class.getAttribute() , since here Classname will be of type String .

So, I need a method that converts a class name from a String type to a Class type.

I tried Class.forName() , but that did not work.

+7
source share
3 answers
 Class<?> classType = Class.forName(className); 

Make sure className is the fully qualified name of the class, for example com.package.class . Also report your error message.

+16
source

If the full class name is available, you can get the corresponding class using the static method Class.forName ().

For example:

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

Note. . Make sure the parameter you provide for this function is the fully qualified class name, such as com.package.class

Check here for any reference.

EDIT:

You can also try using the loadClass() method.

For example:

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

It calls the Java virtual machine to resolve class references.

Syntax:

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

Learn more about ClassLoader here.

Here is an implementation of ClassLoader.

+1
source

Please try the following.

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

All Articles