I am trying to load a java.class file dynamically and call it reflection.
I have a class called Foo; it has an empty constructor and has one method called doit () that takes a String argument and returns a string. It also changes the direction of the line.
Here is my code:
URL url = new URL("file://C:/jtest/"); URLClassLoader loader = new URLClassLoader(new URL[]{url}); Class<?> cl = loader.loadClass("Foo"); Constructor<?> cons = cl.getConstructor((Class[])null); Object ins = cons.newInstance(new Object[]{}); Method meth = cl.getDeclaredMethod("doit", String.class); Object ret = meth.invoke(ins, new Object[]{"!dlroW olleH"}); System.out.println((String)ret);
As expected, this prints "Hello World!" However, it takes 30 seconds to complete. I know that reflection is slow, but I expect it to be 10 ms or something like that.
I am using Eclipse with JRE 1.6.0_13 and I am running Windows Vista.
What am I doing wrong here?
Thanks.
Edit: I have profiled the code, and all its time is used in the third line (loadClass ()). Everything else happens instantly.
Edit: I put the code in a loop; the slow function is somehow optimized and takes 30 seconds only in the first cycle.
Edit: I found a solution.
Instead:
URL url = new URL("file://C:/jtest/");
I changed it to:
URL url = new URL("file:/C:/jtest/");
Now it works great. I donβt know why this works, but I donβt understand how I (and 5 more people) could have missed it. Now I feel stupid.
java performance reflection
Lucky
source share