I have a piece of existing code that works using reflection, but I'd like to start creating the objects using dependency injection and Guice, if possible.
Here's how it currently works:
- Configuration (
.properties
) file is loaded, with a string likeobjects=Foo,^ab..$;Bar,^.bc.$;Baz,i*
- Note:
Foo
,Bar
, andBaz
are classes that implementMyInterface
- Each pair has a regular expression paired with it.
- Input data is fed in from another source. Imagine for this example, the data is:
String[]{ "abab", "abcd", "dbca", "fghi", "jklm" }
- I then want to create new instances of
Foo
,Bar
andBaz
that are created by Guice.- The instances created, in this case, would be:
new Foo("abab");
new Foo("abcd");
new Bar("abcd");
new Bar("dbca");
new Baz("fghi");
"jklm"
would not create any new instances, as it has no matching pattern.
- The instances created, in this case, would be:
Here's how it works currently (this is the best I could do sscce-wise), using reflection:
public class MyInterfaceBuilder {
private Classloader tcl = Thread.currentThread().getContextClassLoader();
private Pattern p;
private Class<? extends MyInterface> klass;
public InterfaceBuilder(String className, String pattern) {
this.pattern = Pattern.compile(pattern);
this.klass = makeClass(className);
}
private static Class<? extends Interface> makeClass(String className) {
String fullClassName = classPrefix + className;
Class<?> myClass;
try {
myClass = tcl.loadClass(fullClassName);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Class not found: " + fullClassName, e);
}
if(MyInterface.class.isAssignableFrom(myClass)) {
return (Class<? extends MyInterface>) myClass;
} else {
throw new IllegalArgumentException(fullClassName + " is not a MyInterface!");
}
}
public MyInterface makeInstance(String type) {
if (pattern == null || pattern.matcher(type).find()) {
MyInterface newInstance = null;
try {
newInstance = klass.getConstructor(String.class).newInstance(type);
} catch (Exception e) {
// Handle exceptions
}
return newInstance;
} else {
return null;
}
}
}
How can I duplicate this functionality (loading the classes dynamically at run-time, and creating exactly the matching instances) having using Guice?