Mina Fouad
Mina Fouad

Reputation: 79

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

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

Upvotes: 0

Views: 3932

Answers (2)

BalusC
BalusC

Reputation: 1108642

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.

Upvotes: 6

user467871
user467871

Reputation:

Did you mean this ?

Class c = Class.forName("java.lang.String");

Upvotes: 2

Related Questions