How to convert String type to Class type in java

前端 未结 3 1054
遇见更好的自我
遇见更好的自我 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:31
    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 16:38

    Please try as following.

    String str = "RequiredClassName";    
    Class <?> Cref = Class .forName("PackageNaem."+str );
    
    0 讨论(0)
提交回复
热议问题