Search code examples
javagenericsdynamic-class-creation

java generics vs dynamically loading class using Class.forName()


Assume I am making a class called Government. Government has members like officers, ministers, departments etc. For each of those members I create an interface, and any specific government defines them as they like.

The main method in the Government class is called Serve(Request req). Assume that the query rate is very large (1000+ queries per second).

To create the government, I can:
1) Use Java generics to write Government<Class Minister, Class Officer, ...> and any specific government implementation needs to create its own Government object in java code, and a main() to have deployable jar.

2) Have a configuration file which specifies the class names of officers, ministers etc., and whenever Serve() is called, it uses Class.forName()and Class.newInstance() to create an object of the class. Any new government just needs to write classes for its members, and the configuration file. There is one single main() for all governments.

From a purely performance point of view - which is better and why? My main concerns are:

a) does forName() execute a costly search every time? Assume a very large universe of classes.

b) Do we miss out on the compiler optimizations that might be performed in case 1 but not in case 2 on the dynamic classes?


Solution

  • As long as you reuse your goverment object, there is no difference at runtime. Difference isonly at object creation time.

    1 & 2 differ in concept - 1 ist hardwired, while 2 is dynamic ( you may even use DI contrainers like spring, guice or pico - basically you proposed to write your own )

    As for forName() performance - it is up on classloader ( and also on container ) . MOst of them would cache name resolution results, look up in map - but I can not speak for all

    As for optimisations - there are compiler optimisations, and also agressive runtime optiomisations from JIT compilers - they matter more.