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.
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.
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.
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.
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.
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.
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