您的位置:首页 > 编程语言 > Java开发

Java通过反射实现实例化

2013-08-25 20:42 411 查看
public static void main(String[] args) throws Exception {

User user= (User) test(User.class);
System.out.println(user.getMoney());
invokeTest(user,"getMoneyT");
}

/**通过反射获取实例
* @param clazz类,如user.class
* @return 类实例
* @throws Exception
*/
static Object test(Class clazz) throws Exception{
//clazz.newInstance();//实例化一个类,前提是该类存在无参构造参数
Constructor constructor=clazz.getConstructor(String.class);//得到构造器,String.class是即将实例化类clazz的构造参数的类型
Object obj= constructor.newInstance("test");//传入一个参数进行实例化
return obj;
}
/**调用指定方法
* @param obj对象
* @param methodName要调用的方法名
* @throws Exception
*/
static void invokeTest(Object obj,String methodName) throws Exception{
Method[] ms= obj.getClass().getDeclaredMethods();//当前类的方法,包括私有
//ms=obj.getClass().getMethods();//子类 父类的所有公共方法
for(Method m:ms){
System.out.println(m.getName());
if (m.getName().equals(methodName)) {
m.invoke(obj, null);//调用无参方法
}

}
Method methods=obj.getClass().getMethod(methodName, null);//根据方法名和参数直接调用方法,方法无参传null
methods.invoke(obj, null);
}
/**通过反射获取字段
* @param clazz
* @throws Exception
*/
static void filed(Class clazz) throws Exception{
Field[] fs=clazz.getDeclaredFields();//当前类的字段,包括私有
//fs=clazz.getFields();//所有公共字段
for (Field field : fs) {
System.out.println(field.getName());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: