I am trying to dynamically load ~10,000 classes and have code which looks like:
Class<?> c = getClass().getClassLoader().loadClass(className);
Constructor<?> constr = c.getConstructor(String.class);
constr.newInstance(myString);
On profiling, I noticed that majority of the time is spent in getConstructor
call which seems to be taking in the order of 15ms on an average, which obviously multiplied by 10k adds up.
Any suggestions on writing this alternatively to speed up java reflection ?
p.s. Unfortunately, these classes do have to be loaded dynamically (otherwise I would not have used reflection at all)
Presumably it is initialising the class that costs. This can be checked by changing .loadClass(className)
to .loadClass(className, true)
. If they are generated classes then perhaps there is something you could change, for instance replacing large literal arrays on static fields with common code to extract the data from string literals.
Edit: Just checked, that flag is resolving (linking). Class.forName(className, true, loader)
to initialise? Mucky mess.
If you want to try method handles, the code would look something along the lines of:
MethodType methodType = MethodType.methodType(
Void.TYPE, String.class
);
MethodHandles.Lookup lookup = MethodHandles.publicLookup();
... for each class ...
lookup.findConstructor(c, methodType).invokeExact(myString);