Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...