Java Class.forName() from distant directory

折月煮酒 提交于 2019-11-26 14:41:33

问题


I am currently loading Java classes using Class.forName() to load it.

clazz = Class.forName("interfaces.MyClass");

But now I want to load classes from different directory, I have tried to set classpath by

clazz = Class.forName("-cp \"C:/dir\" distantinterfaces.DistantClass");

With no success and ClassNotFoundException. Full path to distant class is:

C:/dir/distantinterfaces/DistantClass.class

回答1:


Use an URLClassLoader for this. The code might be something along the lines of:

File f = new File("C:/dir");
URL[] cp = {f.toURI().toURL()};
URLClassLoader urlcl = new URLClassLoader(cp);
Class clazz = urlcl.loadClass("distantinterfaces.DistantClass");



回答2:


Either the directory is in the classpath, and you can use Class.forName() (which only accepts fuly qualified name classes, and not -cp command line options), or it's not in the classpath and you should then use a custom class loader.

You're not saying what you really want to do (why are you loading classes dynamically), but your best bet is to have the directory in the classpath.




回答3:


You have to create an instance of ClassLoader which is aware of the directory with classes. See stackoverflow questions tagged urlclassloader.



来源:https://stackoverflow.com/questions/16335305/java-class-forname-from-distant-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!