[英]How to Dynamically call a method of a class if class name is passed as string
我想創建動態 object 以便調用 class 的相應方法。 所有類和接口都在不同的文件中,但在同一個文件夾下給定:
interface Method
{
public void display();
}
class Car implements Method
{
public void display()
{
System.out.print("Car method");
}
}
class Honda implements Method
{
public void display()
{
System.out.print("Honda method");
}
}
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
String className = "Car";
Class cls = Class.forName(className);
Method method = (Method) cls.getConstructor().newInstance();
method.display();
}
}
現在,如果在字符串中傳遞 Honda,那么我想調用字符串方法,但是如果我在字符串中傳遞 Car,那么我想將 Car 方法作為 output 但是在編譯后這個方法不會被調用。 沒有錯誤,但也沒有預期的 output。 如何獲得所需的 output。 請幫忙。
您可以調用所需的方法。
Method method = cls.getMethod("display");
method.invoke(parameters);
如果允許我更新上述代碼,則如下所示,
interface Car
{
public void display();
}
class Honda implements Car
{
public void display()
{
System.out.print("Car method");
}
}
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
String className = "Car";
Class cls = Class.forName(className);
Honda honda = (Honda)cls.newInstance()
honda.display();
}
}
希望這將清除我在上面的答案中提到的Method
class 的事情。
方法class.newInstance()已被棄用。 所以你應該使用
Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class).newInstance();
Object object = ctor.newInstance(ctorArgument);
SN:在這種情況下,我假設構造函數只有一個 String 參數值。 必須調用getConstructor
方法,傳遞所需構造函數具有的所有 class 類型(正確排序)。 使用 newInstance 時,您需要傳遞實際構造函數的 args 值
此時,您必須使用getMethod()
獲取方法,該方法需要方法名稱和所有參數的類型。 要實際調用該方法,請傳遞要調用該方法的 object 的實例(在本例中,我們的object並傳遞實際參數的值以調用它
clazz.getMethod("methodName", String.class, String.class).invoke(object, "parameter1", "parameter2");
編輯:OP 更新了兩個類實現公共接口的問題。 在這種情況下,您實際上可以調用您知道將讓每個 class 實現該接口的方法。 這樣,除了創建 object 本身的新實例之外,您不必使用任何反射魔法
使用通用接口
Method method = (Method) Class.forName(className).getConstructor().newInstance();
method.display();
最后一行會調用實現接口的object實例的display方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.