反射:
//通过类名来构造一个类的实例 Class cls_str = Class.forName("java.lang.String"); //上面这句很眼熟,因为使用过JDBC访问数据库的人都用过J Object str = cls_str.newInstance(); //相当于 String str = new String(); |
//通过方法名来调用一个方法 String methodName = "length"; Method m = cls_str.getMethod(methodName,null); System.out.println("length is " + m.invoke(str,null)); //相当于System.out.println(str.length()); |
内省
什么是Java内省:内省是Java语言对Bean类属性、事件的一种缺省处理方法。
Java内省的作用:一般在开发框架时,当需要操作一个JavaBean时,如果一直用反射来操作,显得很麻烦;所以sun公司开发一套API专门来用来操作JavaBean
- package com.javax.iong.javabean0301;
-
- public class Person {
-
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- private int age;
-
- }
- package com.javax.iong.javabean0301;
-
- import java.beans.BeanInfo;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.Method;
-
- import org.junit.Test;
-
- public class Test1 {
-
- @Test
- public void tes1() throws Exception {
- Class<?> cl = Class.forName("com.javax.iong.javabean0301.Person");
-
- BeanInfo beaninfo = Introspector.getBeanInfo(cl, Object.class);
- PropertyDescriptor[] pro = beaninfo.getPropertyDescriptors();
- Person p = new Person();
- System.out.print("Person的属性有:");
- for (PropertyDescriptor pr : pro) {
- System.out.print(pr.getName() + " ");
- }
- System.out.println("");
- for (PropertyDescriptor pr : pro) {
-
- Method writeme = pr.getWriteMethod();
- if (pr.getName().equals("name")) {
-
- writeme.invoke(p, "xiong");
- }
- if (pr.getName().equals("age")) {
- writeme.invoke(p, 23);
- }
-
- Method method = pr.getReadMethod();
- System.out.print(method.invoke(p) + " ");
-
- }
- }
-
- @Test
- public void test2() throws Exception {
- PropertyDescriptor pro = new PropertyDescriptor("name", Person.class);
- Person preson=new Person();
- Method method=pro.getWriteMethod();
- method.invoke(preson, "xiong");
- System.out.println(pro.getReadMethod().invoke(preson));
- }
- }
========================================================
内省中,Apache提供了工具
commons-beanutils-1.7.0.jar
BeanUtils.setProperty(pt1, "x", "9");
System.out.println(pt1.getX());
BeanUtils.setProperty(pt1, "birthday.time", "111");
System.out.println(BeanUtils.getProperty(pt1, "birthday.time"));
PropertyUtils.setProperty(pt1, "x", 9);
System.out.println(PropertyUtils.getProperty(pt1, "x").getClass().getName());
BeanUtils.setProperty(pt1, "x", "9");
System.out.println(pt1.getX());
BeanUtils.setProperty(pt1, "birthday.time", "111");
System.out.println(BeanUtils.getProperty(pt1, "birthday.time"));
PropertyUtils.setProperty(pt1, "x", 9);
System.out.println(PropertyUtils.getProperty(pt1, "x").getClass().getName());