Search code examples
javaclassloader

How to us a custom ClassLoader to get different and new objects from a library in Java


I want to get new instances of classes that exist inside a library. The library has different classes inherited from one parent class, and I need to get new instances of the child classes. I can provide precisely the class name as a text.

More specifically, I need to create objects of different HL7-v2 messages types from the hapi-base library. It has AbstractMessage class as the parent, while its child classes are ADT_A01, ADT_A02,... etc. I need to create ADT_A01(), ADT_A02()...etc objects from it.

How can I achieve this by using a Class Loader? If not, why?


Solution

  • Class hl7MessageClass = getClass().getClassLoader().loadClass("package_name"+hl7MessageType);
    return (AbstractMessage) hl7MessageClas.newInstance();