欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA反射与内省(Introspector)

程序员文章站 2024-01-20 15:53:34
...

什么是Java内省:内省是Java语言对Bean类属性、事件的一种缺省处理方法。

Java内省的作用:一般在开发框架时,当需要操作一个JavaBean时,如果一直用反射来操作,显得很麻烦;所以sun公司开发一套API专门来用来操作JavaBean.

反射就是运行时获取一个类的所有信息,可以获取到.class的任何定义的信息(包括成员 变量,成员方法,构造器等)
可以操纵类的字段、方法、构造器等部分。
内省基于反射实现,主要用于操作JavaBean,通过内省 可以获取bean的getter/setter


1. 内省

private static void tetsJavaIntrospector() throws Exception{
		Class<?> cl = Class.forName("yiban.dao.Person");  
        // 在bean上进行内省  
        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) {  
            // 获取beal的set方法  
            Method writeme = pr.getWriteMethod();  
            if (pr.getName().equals("name")) {  
                // 执行方法  
                writeme.invoke(p, "xiong");  
            }  
            if (pr.getName().equals("age")) {  
                writeme.invoke(p, "23");  
            }  
            // 获取beal的get方法  
            Method method = pr.getReadMethod();  
            System.out.print(method.invoke(p) + " ");  
  
        }  
	}

package yiban.dao;

Person:

public class Person {
	private String name;
	private String age;
    public String amount;
	public Person() {
		super();
	}

	public Person(String name){
		this(name,null);
	}
	
	public Person(String name, String age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}

	
	public String getAmount() {
		return amount;
	}

	public void setAmount(String amount) {
		this.amount = amount;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return super.clone();
	}

	
}


2. 反射

反射详解参考: https://www.cnblogs.com/jalja/p/6084445.html

向原作者致敬,如有需要联系本人删除即可.



从上面引出一个例子:

java 使用BeanInfo实现bean实体与map之间的互相转换

java 使用BeanInfo实现bean实体与map之间的互相转换。 
public interface BeanInfo希望提供有关其 bean 的显式信息的 bean 实现者可以提供某个 BeanInfo 类,该类实现此 BeanInfo 接口并提供有关其 bean 的方法、属性、事件等显式信息

转载: http://blog.csdn.net/cuiyaoqiang/article/details/53582382

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.bh.bean.User;

public class Test {

    /**
     * bean转map
     */
    public Test() {
        try {
            Map<String, Object> user=beanTransformToMap(new User(1, "zs"));
            Iterator<Entry<String, Object>> iterator = user.entrySet().iterator();
            while(iterator.hasNext()){
                Entry<String, Object> next = iterator.next();
                System.out.println(next.getKey()+" "+next.getValue());
            }

        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                | IntrospectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**map转实体
     * @param map
     * @return
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @throws IntrospectionException
     */
    private User mapTransformToBean(Map<String, Object> map) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{

        User user=new User();
        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass());  
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
        for (PropertyDescriptor property : propertyDescriptors) {  
            String key = property.getName();  
            if (map.containsKey(key)) {  
                Object value = map.get(key);  
                //得到property对应的setter方法  
                Method setter = property.getWriteMethod();  
                setter.invoke(user, value);  
            }  
        }
        return user;  
    }
    /**实体转map
     * @param user
     * @return
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @throws IntrospectionException
     */
    private Map<String, Object> beanTransformToMap(User user) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{

        Map<String, Object> map = new HashMap<String, Object>();
        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass());  
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
        for (PropertyDescriptor property : propertyDescriptors) { 
            String key = property.getName();  
            // 过滤class属性  
            if (!key.equals("class")) {  
                // 得到property对应的getter方法  
                Method getter = property.getReadMethod();  
                Object value = getter.invoke(user);  
                map.put(key, value);  
            }  
        }
        return map;  
    }
    public static void main(String[] args) {

        new Test();
    }
}