Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String type to Class type in java

Tags:

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.

like image 366
Bipin Wanchoo Avatar asked Sep 05 '12 17:09

Bipin Wanchoo


People also ask

How do you convert a string to a class object?

We can also convert the string to an object using the Class. forName() method. Parameter: This method accepts the parameter className which is the Class for which its instance is required. Return Value: This method returns the instance of this Class with the specified class name.

How do I convert a string to an object in java?

In Java, a String can be converted into an Object by simply using an assignment operator. This is because the Object class is internally the parent class of every class hence, String can be assigned to an Object directly. Also, Class. forName() method can be used in order to convert the String into Object.

Can we convert string to int in java?

We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns instance of Integer class.


2 Answers

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.

like image 172
Piyush Mattoo Avatar answered Sep 27 '22 15:09

Piyush Mattoo


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.

like image 29
heretolearn Avatar answered Sep 27 '22 15:09

heretolearn