我有用於返回對象實例的方法。使用反射獲得類實例很好。 我需要避免每次爲同一個類創建一個新對象。 我錯過了什麼?如何防止使用反射創建多個對象
private static Object getInstance(String clazz)
{
//full path of the class in the clazz
Class<?> c = null;
Object obj = null;
try
{
c = Class.forName(clazz);
System.out.println("inside ins" + c);
obj = c.newInstance();
}
catch (Exception e)
{
System.out.println(e);
}
return obj;
}
Object inst = getInstance("com.test.Test1");
Method method = inst.getClass().getMethod("getVal", String.class,String.class);
method.invoke(inst, "new params","ss");
感謝
聽起來像你需要一個'Map'作爲緩存,基本上...... –
你可以檢查instanceOf方法。 – Gopal00005
...或使用IoC容器 –