[英]java C# vb: how do we dynamically create an instance of a class from a string input (class name)
[英]How to dynamically create an instance in java, from string with parameters?
我知道這個問題會在一段時間后得到解答。 但是參數一直都是對象。 那就是我要替換的東西:
if (s.equals("A")) { add (obj = new A(x,y)); }
if (s.equals("B")) { add (obj = new B(x,y)); }
if (s.equals("C")) { add (obj = new C(x,y)); }
我有這個:
try
{
Class cl = Class.forName(s);
Constructor con = cl.getConstructor (x, y);
obj = con.newInstance(x, y);
}
但它期望x,y作為一個類,但它是一個int。 怎么做>
你需要
cl.getConstructor(int.class, int.class);
有Class
對象反映原始類型,甚至void
類型在Void.class
都有對應的反射對象。
您需要使用:
cl.getConstructor(int.class,int.class);
獲得帶有(int,int)
參數的構造函數。
如果x和y是int
,請嘗試通過傳遞受保護參數的類型來調用getConstructor
:
Class cl = Class.forName(s);
Constructor con = cl.getConstructor (Integer.TYPE, Integer.TYPE);
obj = con.newInstance(x, y);
您需要為getConstructor方法提供類型。 那是
Constructor con = cl.getConstructor (x.getClass(), y.getClass());
要么
Constructor con = cl.getConstructor (ClassOfX.class, ClassOfY.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.