How to convert String type to Class type in java

前端 未结 3 1060
遇见更好的自我
遇见更好的自我 2020-12-17 16:15

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 t

3条回答
  •  不知归路
    2020-12-17 16:35

    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.

提交回复
热议问题