簡體   English   中英

檢查一個方法在Java上有多少個參數

[英]Check how many arguments a method has on Java

我有多個類擴展了抽象類A。

抽象類具有以下方法:

public abstract int methodOne (int n);
public abstract int methodTwo (int n);

擴展類A的類之一B類覆蓋了以下方法之一,例如:

public int methodOne (int n) {
    return n * 2;
}

public int methodOne (int n, int k) {
    return n * k;
}

現在,我們正在使用類B的實例,是否有方法檢查方法“ methodOne”是否已重載,然后進行檢查。

A ourTest = new B();

如果methodOne有兩個參數,則將方法與兩個參數一起使用,否則,將methodOne與一個參數一起使用。

您可以使用反射來檢查B聲明的方法。 請注意,有2種口味:

B.getClass().getMethods()

將為您提供代表該類所有公共方法的Method對象數組,包括由類或接口聲明的方法以及從超類和超接口繼承的方法。

你也可以打電話

B.getClass().getDeclaredMethods()

將為您提供一個包含Method對象的數組,該對象反映該類的所有已聲明方法,包括public,protected,默認(包)訪問和私有方法, 但不包括繼承的方法

並不是說您的情況是,類A沒有methodOne的2參數形式,因此從技術上講,不能在B繼承或覆蓋它。

因此,您可以調用getDeclaredMethods()並遍歷Method對象的數組,以查看B是否具有methodOne的2參數形式。

即使您聲明了A類型的對象,但使用new B()實例化了它,該方法也有效

下面的示例代碼展示了它的實際作用:

public abstract class A {
   public abstract int methodOne (int n);
   public abstract int methodTwo (int n);
}

public class B extends A {
   @Override
   public int methodOne(int n) {
      return n;
   }

   public int methodOne(int n, int k) {
      return n + k;
   }

   @Override
   public int methodTwo(int n) {
      return n * 2;
   }
}

// test it out (note that this can throw several different exceptions
// so you'll have to handle them..I left that out to keep the code
// concise.

A a = new B();
Method[] methods = a.getClass().getDeclaredMethods();

for(Method m : methods) {
    System.out.println(m.toGenericString());
    if(m.getName().equals("methodOne") && m.getParameterCount() == 2) {
        int result = (int)m.invoke(a, 3, 2);
        System.out.println("Result = " + result);
    }
}

這將打印以下內容:

public int B.methodTwo(int)
public int B.methodOne(int,int)
Result = 5
public int B.methodOne(int)

您沒有帶有一個或兩個參數的相同方法。 兩種方法雖然名稱相同(methodOne),但均不同。 如果要查找一個方法有多少個自變量,或者是否要重載該方法,可以使用Java Reflection API。 但是您試圖做的事似乎沒有任何意義。

如果methodOne有兩個參數,則將方法與兩個參數一起使用,否則,將methodOne與一個參數一起使用。

不,您不能這樣做,因為Java是靜態類型的。

由於A僅定義methodOne的單參數版本,因此對於使用A類型變量的代碼,您將擁有全部。

添加到子類中的任何方法在A類型變量的純Java代碼中都不可見。 您只能通過強制轉換為所討論的子類或使用反射來調用此類“額外”方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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