0

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

1

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

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • Thank you for your reply. The thing is, I am trying to use ClassLoader here without external libraries. – Dulaj Kavinda Jul 20 '22 at 04:14
  • To solve your problem not only you don't need to use ClassLoader but you actually can't use it. ClassLoader loads classes into memory and you already have your classes in the memory. Note that my answer split into 2 parts. If you don't want to use 3d party library just ignore the 2d part. But to sole your problem you will need to use Factory pattern. and for that you don't need any external library. (See the 1st part of my answer) – Michael Gantman Jul 20 '22 at 07:56
  • @DulajKavinda you don't need to use the ClassLoader in this case, your classes are most likely already loaded. `java.lang.ClassLoader#loadClass(java.lang.String, boolean)` will just find the already loaded class and return it. In that case it would be easier to just call `java.lang.Class#forName(java.lang.String)`. – slindenau Jul 22 '22 at 07:41
0
Class hl7MessageClass = getClass().getClassLoader().loadClass("package_name"+hl7MessageType);
return (AbstractMessage) hl7MessageClas.newInstance();
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197