[英]Creating objects from strings
所以我從 XML 中讀取了一些數據:
String arg1Value;
String arg2Value;
String arg2TypeAsString;
String arg1TypeAsString;
我想創建一個對象: ObjectType(arg1Type, arg2Type);
我正在嘗試這個:
(ObjectType) Class.forName(arg1TypeAsString).getConstructor(arg1Type.class, arg2Type.class).newInstance(arg1Value, arg2Value)
但這給了我一個noSuchMethodException: ObjectType.<init>(arg1Type, arg2Type)
請注意,我正在嘗試創建不同的對象,但它們都從 ObjectType 擴展,並且它們的所有參數分別從 arg1Type 和 arg2Type 擴展。
鑒於規范有點模糊(沒有實際代碼),請嘗試以下操作:
private
、 protected
或 default 包修飾符,如果有,請改用getDeclaredConstructor()
ObjectType
類定義默認構造函數將您的語句拆分為多行:
Class<ObjectType> otClass = (ObjectType) class.forName(arg1TypeAsString); Constructor<ObjectType> otConstructor = otClass.getConstructor(arg1Type.class, arg2Type.class); ObjectType ot = otConstructor.newInstance(arg1Value, arg2Value);
我最初的假設是應該使用對象數組調用newInstance
。 這是不正確的,請參閱下面的評論。 那么可能的原因是您將原始類型傳遞給newInstance
例如int
而不是Integer
。 自然地創建對象數組將消除這種可能性。 最后,我設法通過從目標類中刪除構造函數來復制錯誤消息,因此無法找到它
java.lang.NoSuchMethodException: Foo.<init>(java.lang.String, java.lang.String)
請查看實現拋出的所有異常。 請創建您的ObjectType
編譯它並將其放置在類路徑中,以便可以找到它。 這是我返回Object
的方法的實現,您可以將其轉換為所需的類型
static Object createInstance(String clsName, String ctorType1, String ctorVal1, String ctorType2, String ctorVal2)
throws ClassNotFoundException, NoSuchMethodException, InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
return Class.forName(clsName).getConstructor(Class.forName(ctorType1), Class.forName(ctorType2))
.newInstance(new Object[]{ctorVal1, ctorVal2});
}
它經過測試並有效。 要捕獲的異常很少。 您可能需要調整參數類型,使其符合您的設計要求。 這是我的測試課
public class Foo {
public Foo(String in, String out){}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.