JAVA反射与内省(Introspector)

什么是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();
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值