Dynamically Loading and Updating Classes in Java

Question:

Is it possible in Java to implement dynamic class update? For example, a class is loaded into the application, but after a while you need to update it to a newer modification without restarting the entire application.

Answer:

Yes, what are the problems?

ClassLoader classLoader = MyClass.class.getClassLoader();
Class myNewClass = classLoader.loadClass("mydomain.MyNewClass");

It is assumed that the object MyNewClass lies in the CLASSPATH , although it is possible without it. You can even compile MyNewClass from source 🙂

Further, having the variable myNewClass with the help of reflection, you can already renumber the new methods and call what you need.

Update:

Simple examples of reflection:

Method[] methods=myNewClass.getMethods(); //список публичных методов класса
Method method=myNewClass.getDeclaredMethod("getMyMethod", String.class); //получаем метод getMyMethod(String )
Constructor[] constructors=myNewClass.getConstructors(); //список конструкторов
//ну и т.п.

Further, I hope it is already clear? There is a constructor, there are methods: we create an object, call its methods, etc.

Scroll to Top