查了下J2SE的API newInstance()方法只能实现无参数的构造函数。原文摘抄如下Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.
如:
java.util.Date date = Class.forName("java.util.Date");
相当于
java.util.Date date = new java.util.Date();另外要注意捕获ClassNotFoundException异常例:
try
{
java.util.Date date = Class.forName("java.util.Date");
}catch(ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
}
try
{
java.util.Date date = (java.util.Date)Class.forName("java.util.Date").newInstance();
}catch(Exception cnfe)
{
cnfe.printStackTrace();
}
public class Test {
public String func(){
return "哈哈哈!你调用我了!";
}
}以下是使用方法public class RefectTest {
public static void main(String[] args) { try {
Class c = Class.forName("Test");//这里你可以从配置文件读入类名
Method[] method = c.getMethods();//获取该类的所有的public方法
for (int i = 0; i < method.length; i++) {
System.out
.println("Method Name:" + method[i].getName()
+ " return Type:"
+ method[i].getReturnType().getName());
}
Method m = c.getMethod("func", null);//准备调用函数,前面是函数名称,后面是参数数组
String s=(String)m.invoke(c.newInstance(), null);//动态调用该函数
System.out.println("函数返回值:"+s);//打印返回值
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}以上我只用了5分钟看JDK的API Document,所以我建议你也看看,你就什么都明白了。
楼主说是动态地使用对象名
我想这个直接的好象不太能实现哦
你可以考虑用HashMap(“动态名字”,对象)
对象可以考虑是单例的
用Class.forName()载入类对象 再用.newInstance()方法产生一个类的实例对象我想问:若构造函数有参数,用.newInstance()那又怎样处理呢?
请各位再回答,先谢了