[英]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.