Make instance of class in java at runtime

2019-07-31 17:45发布

问题:

In my program I generate classes dynamically but when I try:

String[] args = {"-d","D:\\path\\build\\classes","-s","D:\\path\\src","http://services.aonaware.com/DictService/DictService.asmx?WSDL"};
WsImport.doMain(args);
URL url = new URL("file:D:/path/build/classes/com/aonaware/services/webservices/");
URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url});
Class service = Class.forName("com.MyClass",true,urlClassLoader );

I recieve java.lang.ClassNotFoundException

If I run one more time the program (in Eclipse), then it is working. Actually I only have to refresh the project in Eclipse and then its working

Does anybody see the problem

回答1:

Sounds like a classpath issue. Make sure that the class in question (or the jar containing it) is compiled and is in the classpath.

What exactly do you mean by "generating classes dynamically"? If you generate the java source file for a class, it needs to be compiled first into a class file, before the classloader can pick it up. Maybe Eclipse does that in the second round, that's why it is working then.



回答2:

You would generally use a ClassLoader like URLClassLoader to load classes dynamically at runtime.



回答3:

Use the three argument form of Class.forName() which requires you specify the ClassLoader. [Java API Link][1]

[1]: http://java.sun.com/javase/6/docs/api/java/lang/Class.html#forName(java.lang.String, boolean, java.lang.ClassLoader)



回答4:

Read the docs on URLClassLoader: Any URL that ends with a '/' is assumed to refer to a directory.

Also, you probably should use '/' as a separator instead of \\.

Addendum:

Well, your code works perfectly for me -- if there are actual compiled Java classes in the directory specified as an URL. But when you say

In my program I generate classes dynamically

do you generate Java source or bytecode directly? If it's source code, do you also compile it from your app?