Dulaj Kavinda
Dulaj Kavinda

Reputation: 1

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?

Upvotes: 0

Views: 345

Answers (2)

Dulaj Kavinda
Dulaj Kavinda

Reputation: 1

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

Upvotes: 0

Michael Gantman
Michael Gantman

Reputation: 7792

You don't need to use class loader. You need to use Factory pattern. You need to create a Factory class that has a method get instance that returns the interface or abstract parent class and receives a parameter such as concrete class name or other identifier and the method will return the concrete class. That's a Factory pattern description in a nutshell. Here is just one link about the pattern: Factory method design pattern in Java, there are many more.

Also, I wrote a feature that I called Self-populating factory. you might be interested in using something like this. Here is the article about the feature: https://dzone.com/articles/non-intrusive-access-to-quotorphanedquot-beans-in. This feature (and some other interesting ones) is available in Open source java library called MgntUtils which is written and maintained by me. You can get it as Maven artifacts or on Github (including source code and Javadoc). And Here is a link to the library Javadoc

Upvotes: 1

Related Questions