how to use reflection package to create an object from a classpath

后端 未结 2 795
时光说笑
时光说笑 2021-01-26 01:30

I want to create an object I know only its classpath Any help will be appreciated.

相关标签:
2条回答
  • 2021-01-26 02:11

    If you have the full qualified classname in a String, use Class#forName() and Class#newInstance().

    Object o = Class.forName("com.example.Foo").newInstance();
    

    This however requires the class to be already present in the classpath and have a (implicit) default constructor.

    If it is not, and you have the class' location in an URL, then use URLClassLoader and pass it to another Class#forName() method which accepts it as an argument.

    URL url = getItSomehow();
    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { url });
    Object o = Class.forName("com.example.Foo", true, classLoader).newInstance();
    

    Or, if you have it in a File instead, then convert it to URL first:

    File file = getItSomehow();
    URL url = file.toURI().toURL();
    // Continue with URLClassLoader.
    
    0 讨论(0)
  • 2021-01-26 02:35

    Did you mean this ?

    Class c = Class.forName("java.lang.String");
    
    0 讨论(0)
提交回复
热议问题