Make instance of class in java at runtime

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

String[] args = {"-d","D:\\path\\build\\classes","-s","D:\\path\\src",""};
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


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.

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

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

[1]:, boolean, java.lang.ClassLoader)

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


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?

Need Your Help

Magento find deepest category for each product

mysql magento group-by

On my products grid page, I would like to display for each product the 'deepest' category in which it has been put.

use different types, or use Object?

java object

Sorry for noobish question, but why we even use String, int and others, if we can just use Object as a type?