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

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

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

2条回答
  •  萌比男神i
    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.
    

提交回复
热议问题