小编典典
这行似乎总结了您的问题的症结所在:
问题在于,现在您不能在实现类上调用任何新方法(只能重写),因为您的对象引用变量具有接口类型。
您非常困在当前的实现中,因为不仅必须尝试强制类型转换,还需要定义要在此子类上调用的方法的定义。我看到两个选择:
1. 如其他地方所述,您不能使用类名称的String表示形式将反映的实例转换为已知类型。但是,您可以使用String
equals()测试来确定您的类是否为所需的类型,然后执行硬编码的强制转换:
try {
String className = "com.path.to.ImplementationType";// really passed in from config
Class c = Class.forName(className);
InterfaceType interfaceType = (InterfaceType)c.newInstance();
if (className.equals("com.path.to.ImplementationType") {
((ImplementationType)interfaceType).doSomethingOnlyICanDo();
}
} catch (Exception e) {
e.printStackTrace();
}
这看起来很丑陋,并且破坏了您拥有的漂亮的配置驱动过程。我不建议您这样做,这只是一个例子。
2. 您还有另一个选择是将您的反思从正义Class/
Object创作延伸到包括Method反思。如果可以Class从配置文件中传入的字符串创建,则还可以从该配置文件中传入方法名称,并通过反射Method从Class对象中获取其自身的实例。然后,您可以调用invoke(http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,java.lang.Object
…) )Method,传入您创建的类的实例。我认为这将帮助您获得所需的服务。
这是一些代码作为示例。注意,我已经为这些方法的参数进行了硬编码。您也可以在配置中指定它们,并且需要反思它们的类名以定义它们的Class对象和实例。
public class Foo {
public void printAMessage() {
System.out.println(toString()+":a message");
}
public void printAnotherMessage(String theString) {
System.out.println(toString()+":another message:" + theString);
}
public static void main(String[] args) {
Class c = null;
try {
c = Class.forName("Foo");
Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{});
Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class});
Object o = c.newInstance();
System.out.println("this is my instance:" + o.toString());
method1.invoke(o);
method2.invoke(o, "this is my message, from a config file, of course");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException nsme){
nsme.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
} catch (InstantiationException ie) {
ie.printStackTrace();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
}
}
}
和我的输出:
this is my instance:Foo@e0cf70
Foo@e0cf70:a message
Foo@e0cf70:another message:this is my message, from a config file, of course
2020-09-21