定义一个用户,作为被反射对象;
写一个反射程序:
输出结果:
这里有几个问题:
1.为什么每次都要把参数组织一边,如
2.为什么最后为什么会报错呢
思考下.....
==================================
1> 引用下侯捷对Class的解释:
Class class十分特殊。它和一般classes一样继承自Object,其实体用以表达Java程序运行时的classes和interfaces,也用来表达enum、array、primitive Java types
(boolean, byte, char, short, int, long, float, double)以及关键词void。当一个class被加载,或当加载器(class loader)的defineClass()被JVM调用,JVM 便自动产生一个Class object。
循环是对Class对应参数的定义,每一个参数加载后都会是一个Class(不知道是否应该如此理解,如有错误,请指正);
2.发现age如果为Integer 的话,就可以了
运行结果:
那就是说,构造函数里面,基本类型是不支持反射的;
public class User {
public String username;
private String password;
public static int age = 12;
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public User(String username, int age) {
super();
this.username = username;
User.age = age;
}
public String getUsername() {
return username;
}
public User() {
super();
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void talkName(String myName) {
if (myName != null && myName.length() > 0) {
System.out.println("myname is " + myName);
} else {
System.out.println("myname is " + username);
}
}
public static void talkAge() {
System.out.println("My age is " + age);
}
}
写一个反射程序:
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author <a href="mailto:zhouxiaofeng0710@hotmail.com">xiaofeng.zhouxf</a>
* @version 1.0
* @date 2009-4-20
*/
public class ReflectionTest {
public void fields(Object obj) {
Class clazz = obj.getClass();
Field[] fields = clazz.getFields();
System.out.println("fields; fields num:" + fields.length);
for (Field field : fields) {
System.out.println("fields; field name:" + field.getName());
System.out.println("fields; field modifyers:" + field.getModifiers());
System.out.println("fields; 只能取到共有的属性!");
}
}
public Object getfield(Object obj, String fieldName) {
Class clazz = obj.getClass();
Object object = null;
try {
Field field = clazz.getField(fieldName);
// 取得当前实例的属性
object = field.get(obj);
System.out.println("getfield ; field name:" + field.getName());
System.out.println("getfield ; field value:" + object.toString());
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return object;
}
public Object getStatticfield(String className, String fieldName) {
Class clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Object object = null;
try {
Field field = clazz.getField(fieldName);
// 取得当前类的属性 因为是取静态的,所以可以直接取,如果不是静态的,会报异常
// java.lang.IllegalArgumentException
object = field.get(clazz);
System.out.println("getStatticfield ; field name:" + field.getName());
System.out.println("getStatticfield ; field value:" + object.toString());
System.out.println("getStatticfield ; 取得当前类的属性 因为是取静态的,所以可以直接取,如果不是静态的,会报异常:java.lang.IllegalArgumentException");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return object;
}
public void invokeMethod(Object object, String methodName, Object[] argsParam) {
try {
Class clazz = object.getClass();
Class[] classArgs = new Class[argsParam.length];
int i = 0;
for (Object obj : argsParam) {
classArgs[i++] = obj.getClass();
}
Method method = clazz.getMethod(methodName, classArgs);
method.invoke(object, argsParam);
System.out.println("invokeMethod ; 调用当前类的方法");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException 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();
}
}
public void invokeStaticMethod(String className, String methodName, Object[] argsParam) {
try {
Class clazz = Class.forName(className);
Class[] classArgs = new Class[argsParam.length];
int i = 0;
for (Object obj : argsParam) {
classArgs[i++] = obj.getClass();
}
Method method = clazz.getMethod(methodName, classArgs);
method.invoke(null, argsParam);
System.out.println("invokeMethod ; 调用当前类的方法");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException 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 (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object newInstance(String className, Object[] args) {
Class clazz = null;
Object resObj = null;
try {
clazz = Class.forName(className);
Class[] cArgs = new Class[args.length];
int i = 0;
for (Object obj : args) {
cArgs[i++] = obj.getClass();
}
Constructor cr = clazz.getConstructor(cArgs);
resObj = cr.newInstance(args);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException 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();
}
return resObj;
}
public static void main(String[] args) {
User user = new User();
user.setUsername("Tracy");
ReflectionTest test = new ReflectionTest();
System.out.println("=============取属性==================>>>>>");
test.fields(user);
System.out.println("=============取实例的属性和值==================>>>>>");
String username = (String) test.getfield(user, "username");
System.out.println("getfield ; username:" + username);
System.out.println("=============取类的静态属性和值==================>>>>>");
test.getStatticfield("com.zhouxf.reflection.User", "age");
System.out.println("=============调用类的方法==================>>>>>");
test.invokeMethod(user, "talkName", new String[] { "Tracy" });
System.out.println("=============调用类的静态方法==================>>>>>");
test.invokeStaticMethod("com.zhouxf.reflection.User", "talkAge", new String[] {});
System.out.println("=============创建实例==================>>>>>");
User user1 = (User) test.newInstance("com.zhouxf.reflection.User", new Object[] { "tracy", 36 });
user1.talkName("");
user1.talkAge();
}
}
输出结果:
=============取属性==================>>>>>
fields; fields num:2
fields; field name:username
fields; field modifyers:1
fields; 只能取到共有的属性!
fields; field name:age
fields; field modifyers:9
fields; 只能取到共有的属性!
=============取实例的属性和值==================>>>>>
getfield ; field name:username
getfield ; field value:Tracy
getfield ; username:Tracy
=============取类的静态属性和值==================>>>>>
getStatticfield ; field name:age
getStatticfield ; field value:12
getStatticfield ; 取得当前类的属性 因为是取静态的,所以可以直接取,如果不是静态的,会报异常:java.lang.IllegalArgumentException
=============调用类的方法==================>>>>>
myname is Tracy
invokeMethod ; 调用当前类的方法
=============调用类的静态方法==================>>>>>
My age is 12
invokeMethod ; 调用当前类的方法
=============创建实例==================>>>>>
java.lang.NoSuchMethodException: com.zhouxf.reflection.User.<init>(java.lang.String, java.lang.Integer)
这里有几个问题:
1.为什么每次都要把参数组织一边,如
Class[] classArgs = new Class[argsParam.length];
int i = 0;
for (Object obj : argsParam) {
classArgs[i++] = obj.getClass();
}
2.为什么最后为什么会报错呢
思考下.....
==================================
1> 引用下侯捷对Class的解释:
Class class十分特殊。它和一般classes一样继承自Object,其实体用以表达Java程序运行时的classes和interfaces,也用来表达enum、array、primitive Java types
(boolean, byte, char, short, int, long, float, double)以及关键词void。当一个class被加载,或当加载器(class loader)的defineClass()被JVM调用,JVM 便自动产生一个Class object。
Class[] classArgs = new Class[argsParam.length];
int i = 0;
for (Object obj : argsParam) {
classArgs[i++] = obj.getClass();
}
循环是对Class对应参数的定义,每一个参数加载后都会是一个Class(不知道是否应该如此理解,如有错误,请指正);
2.发现age如果为Integer 的话,就可以了
public class User {
public String username;
private String password;
public static Integer age = 12;
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public User(String username, Integer age) {
super();
this.username = username;
User.age = age;
}
public String getUsername() {
return username;
}
public User() {
super();
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void talkName(String myName) {
if (myName != null && myName.length() > 0) {
System.out.println("myname is " + myName);
} else {
System.out.println("myname is " + username);
}
}
public static void talkAge() {
System.out.println("My age is " + age);
}
}
运行结果:
=============创建实例==================>>>>>
myname is tracy
My age is 36
那就是说,构造函数里面,基本类型是不支持反射的;