0

I have an interface, LogParser, consisting of a single method parse(String x). I also have an ArrayList containing the names of multiple classes which all implement LogParser. Is it possible to loop through this list of class names and dynamically instantiate their respective classes and invoke parse(String x)?

The issue I've had is that the classes do not have zero-argument constructors, so I have run into InstantiationException a lot attempting to invoke the parse method through reflection.

Thanks!

2 Answers2

0

If the implementation types don't have constructors, it will be very painful. The easiest way to do it is probably to use a dependency injection framework like Spring or Guice.

In Spring, you could just inject a List<LogParser>, and you would get all known implementations:

@Autowired
private List<LogParser> parsers;

Now of course you would have to define each of the LogParsers separately as Spring bean.

There is similar functionality in other frameworks as well.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
0

You have to invoke some constructor to instantiate an object usefully. You use reflection to grab the Method for the constructor, and you instantiate with that. See Instantiate a class object with constructor that accepts a string parameter?. I didn't close as duplicate, since you have the additional question: Do you know that all your classes have a constructor with the same signature?

Community
  • 1
  • 1
bmargulies
  • 97,814
  • 39
  • 186
  • 310