[英]Instantiate and use an object with only the textual class name in Java
我在Java的同一包中有幾個類。 我想從具有類名稱作為字符串的數組中實例化這些類的對象。
這是我要使用的類的示例,它們都具有相同的結構。
class Class1 {
public String[] firstMethod(){
String[] data = {"NEW_ITEM"};
return data;
}
}
這是我嘗試從中實例化的類。
class Main {
static {
String[] classes = {"Class1","Class2"};
for (String cls : classes) {
try {
Object o = Class.forName(cls).newInstance();
o.firstMethod();
} catch(ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
System.out.println(ex.toString());
}
}
我的問題是,當我嘗試使用對象o調用firstMethod()時,出現此錯誤。
exit status 1
Main.java:19: error: cannot find symbol
o.firstMethod();
^
symbol: method firstMethod()
location: variable o of type Object
1 error
我懷疑這是因為它是Object類型而不是Class1類型。 我已經看到了將對象轉換為所需類的對象的解決方案。 但是,當您打字時,您需要使用類的名稱,這正是我要避免的名稱。 我需要使用類名作為字符串。
有誰知道一種解決方案,可以在其中使用創建的對象調用方法?
您不能像在代碼中那樣調用方法,因為您有一個不知道Class1類型的對象。 您需要像
((Class1)o).firstMethod()
我認為這不是您想要的。
或者,您可以遍歷對象方法並動態調用它,如下所示:
String[] classes = {"com.yourpackage.Class1", "com.yourpackage.Class2"};
for (String cls : classes) {
try {
Object o = Class.forName(cls).newInstance();
for(Method m : o.getClass().getMethods()) {
System.out.println(m.getName());
if ("firstMethod".equals(m.getName())) {
String[] data = (String[])m.invoke(o, null); // here are the parameters
for(String d : data){
System.out.println(d);
}
}
}
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
System.out.println(ex.toString());
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
輸出為:
NEW_ITEM
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.