簡體   English   中英

使用類名從不同的類調用方法

[英]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參數。

基本上:

  • ClassgetMethod方法采用一個String表示該方法的名稱,並使用Class<?>的varargs表示其參數類型。 我們調用的方法( getInstance )不帶參數,因此getMethod的參數為null,但我們希望將其getMethod為期望的參數。 更多信息在這里
  • Methodinvoke方法以Object為目標實例來調用該方法(在本例中為null因為它是一個類方法),而Object的varargs作為參數。 但是同樣,您的getInstance方法不接受任何參數,因此我們使用null並將其強制轉換為Object數組。 更多信息在這里
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM