[英]Calling methods from different classes with the class name
我有单例模式的各种课程。 它们都是从抽象类扩展而来的。 每个类都有一个getInstance()方法(名称完全相同)。 我想获取具有类名称(字符串)的实例。 例如
public abstract class AbsCls {
}
public class A extends AbsCls {
private static A a;
private A() {
}
public synchronized static A getInstance() {
if(a==null) {
a == new A();
}
return a;
}
public class Test {
public static void main(String[] args) {
AbsCls[] array = new AbsCls[5];
array[0]=neededFunction("A");
array[1]=neededFunction("B");
}
}
所有类都与类A具有相同的结构。needFunction()应该如何?
我可以写“ if .. else”,但是我觉得应该有一个更优雅的方法。 感谢您的任何提前帮助...
您可以在package.ClassName
,Reflection和Class.forName(theName)
使用完整的类名。
例如,使用String
对象:
try {
String newString = (String)Class.forName("java.lang.String").newInstance();
}
catch (IllegalAccessException iae) {
// TODO handle
}
catch (InstantiationException ie) {
// TODO handle
}
catch (ClassNotFoundException cnfe) {
// TODO handle
}
因此,您的方法大致如下所示:
@SuppressWarnings("unchecked")
public static <T> T getInstance(String clazz) {
// TODO check for clazz null
try {
return (T)Class.forName(clazz).getMethod("getInstance", (Class<?>[])null).invoke(null, (Object[])null);
}
catch (ClassNotFoundException cnfe) {
// TODO handle
return null;
}
catch (NoSuchMethodException nsme) {
// TODO handle
return null;
}
catch (InvocationTargetException ite) {
// TODO handle
return null;
}
catch (IllegalAccessException iae) {
// TODO handle
return null;
}
}
编辑 OP:
(Class<?>[])null
和(Object[])null
是转换为预期类型的null
参数。
基本上:
AbsCls[] array = new AbsCls[5]; // this create object for AbsCls
array[0]=neededFunction("A"); // calling method from AbsCls
array[1]=neededFunction("B");// calling method from AbsCls
如果为超类创建对象,则无法从子类获取方法
AbsCls[] array = new A[5]; //this create object for A
如果要调用超类方法用户super
关键字,则可以访问这两个类
array[0]=neededFunction("A"); //// calling method from A
array[1]=super.neededFunction("B");//// calling method from AbsCls
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.