I want to create an object I know only its classpath Any help will be appreciated.
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.
Did you mean this ?
Class c = Class.forName("java.lang.String");