【发布时间】:2013-06-18 13:46:51
【问题描述】:
我有一段使用反射工作的现有代码,但如果可能的话,我想开始使用依赖注入和 Guice 创建对象。
这是它目前的工作方式:
- 配置 (
.properties) 文件已加载,字符串如objects=Foo,^ab..$;Bar,^.bc.$;Baz,i*- 注意:
Foo、Bar和Baz是实现MyInterface的类 - 每一对都有一个正则表达式与之配对。
- 输入数据是从另一个源输入的。想象一下这个例子,数据是:
String[]{ "abab", "abcd", "dbca", "fghi", "jklm" }
- 然后我想创建由 Guice 创建的
Foo、Bar和Baz的新实例。- 在这种情况下,创建的实例将是:
new Foo("abab");new Foo("abcd");new Bar("abcd");new Bar("dbca");new Baz("fghi");-
"jklm"不会创建任何新实例,因为它没有匹配的模式。
- 在这种情况下,创建的实例将是:
这是它目前的工作方式(这是我能做的最好的sscce-wise),使用反射:
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;
}
}
}
如何使用 Guice 复制此功能(在运行时动态加载类,并创建完全匹配的实例)?
【问题讨论】:
标签: java reflection guice