Java内省&PropertyEditor

1.  什么是内省? 

  内省(Introspector)是Java语言对JavaBean类属性、事件的处理方法。
  例如类User中有属性name,那么必定有getName,setName方法,我们可以通过他们来获取或者设置值,这是常规操作。
  Java提供了一套API来访问某个属性的getter/setter方法,这些API存放在java.beans中。

  在计算机科学中,内省是指计算机程序在运行时(Run time)检查对象(Object)类型的一种能力,通常也可以称作运行时类型检查。
  不应该将内省和反射混淆。相对于内省,反射更进一步,是指计算机程序在运行时(Run time)可以访问、检测和修改它本身状态或行为的一种能力。

内省和反射的区别:

  反射是在运行状态把Java类中的各种成分映射成相应的Java类,可以动态的获取所有的属性以及动态调用任意一个方法,强调的是运行状态。 
  内省机制是通过反射来实现的,BeanInfo用来暴露一个bean的属性、方法和事件,以后我们就可以操纵该JavaBean的属性。

我自己的理解是:

  内省更多的用在获取属性以及属性的的getter、setter方法,进行一些其他的操作。

  反射更多的用在反射创建对象以及调用方法等操作。

 

2.  内省类库简介

比如User类:

package cn.qlq;

public class User {

    private int age;

    private String name;

    private Address address;

    private boolean deleted;

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

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

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public boolean isDeleted() {
        return deleted;
    }

    public void setDeleted(boolean deleted) {
        this.deleted = deleted;
    }

}

class Address {

    private String province;

    private String city;

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

主要涉及的类库如下:

(1)Introspector类,可以获取BeanInfo类,常见的使用方法如下: (重要)

        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass());

        // 第二个参数代表停止的类,也就是如果有继承关系不获取第二个参数及其父类的信息
        BeanInfo beanInfo2 = Introspector.getBeanInfo(user.getClass(), Object.class);

(2)BeanInfo类:通过上面的内省类获得 (重要)

        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass(), Object.class);

作用1:获取BeanDescriptor一个全局的类描述信息

        // 获取BeanDescriptor-一个全局的类描述信息
        BeanDescriptor beanDescriptor = beanInfo.getBeanDescriptor();
        System.out.println(beanDescriptor);

作用2:获取所有的PropertyDescriptor属性描述器(如果获取BeanInfo的时候第二个参数没传会获取从Object继承的信息)

    private static void testBeanInfo2(User user) throws Exception {
        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass(), Object.class);

        // 获取PropertyDescriptor描述器
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            // 获取属性类型
            Class<?> propertyType = propertyDescriptor.getPropertyType();
            // 获取属性名称
            String name = propertyDescriptor.getName();
            // 获取属性的读方法,getXXX
            Method readMethod = propertyDescriptor.getReadMethod();
            // 获取属性的写方法,setXXX
            Method writeMethod = propertyDescriptor.getWriteMethod();

            System.out.println(name);
            System.out.println(propertyType);
            System.out.println(readMethod.getName());
            System.out.println(writeMethod.getName());
            System.out.println("==============");
        }
    }

结果:

address
class cn.qlq.Address
getAddress
setAddress
==============
age
int
getAge
setAge
==============
deleted
boolean
isDeleted
setDeleted
==============
name
class java.lang.String
getName
setName
==============

作用3: 获取MethodDescriptor描述器(如果获取BeanInfo的时候第二个参数没传会获取从Object继承的方法)

        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass(), Object.class);

        // 获取MethodDescriptor描述器
        MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
        for (MethodDescriptor methodDescriptor : methodDescriptors) {
            Method method = methodDescriptor.getMethod();
            System.out.println(method);
        }

结果:

public java.lang.String cn.qlq.User.getName()
public void cn.qlq.User.setAge(int)
public void cn.qlq.User.setName(java.lang.String)
public int cn.qlq.User.getAge()
public boolean cn.qlq.User.isDeleted()
public cn.qlq.Address cn.qlq.User.getAddress()
public void cn.qlq.User.setAddress(cn.qlq.Address)
public void cn.qlq.User.setDeleted(boolean)

作用4:获取EventSetDescriptor(这个不常用)

        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass(), Object.class);

        // 获取EventSetDescriptor描述器
        EventSetDescriptor[] eventSetDescriptors = beanInfo.getEventSetDescriptors();
        for (EventSetDescriptor eventSetDescriptor : eventSetDescriptors) {
            System.out.println(eventSetDescriptor);
        }

(3)BeanDescriptor  一个全局的Bean描述信息,一般没啥用

        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass(), Object.class);
        
        // 获取BeanDescriptor-一个全局的类描述信息
        BeanDescriptor beanDescriptor = beanInfo.getBeanDescriptor();
        System.out.println(beanDescriptor);

(4)PropertyDescriptor  属性描述器,可以获取到属性名称、属性的get方法以及set方法,进而做到修改方法。

其获取方式可以通过BeanInfo获取,也可以通过直接new的方式获取。

方式一:

        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass(), Object.class);

        // 获取PropertyDescriptor描述器
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            // 获取属性类型
            Class<?> propertyType = propertyDescriptor.getPropertyType();
            // 获取属性名称
            String name = propertyDescriptor.getName();
            // 获取属性的读方法,getXXX
            Method readMethod = propertyDescriptor.getReadMethod();
            // 获取属性的写方法,setXXX
            Method writeMethod = propertyDescriptor.getWriteMethod();

            System.out.println(name);
            System.out.println(propertyType);
            System.out.println(readMethod.getName());
            System.out.println(writeMethod.getName());
            System.out.println("==============");
        }

方式二:通过直接new的方式

        User user = new User();
        user.setName("zhangsan");

        PropertyDescriptor propertyDescriptor = new PropertyDescriptor("name", User.class);

        // 获取getter方法读取属性
        Method readMethod = propertyDescriptor.getReadMethod();
        Object invoke = readMethod.invoke(user);
        System.out.println(invoke);

        // 获取setter方法修改属性
        Method writeMethod = propertyDescriptor.getWriteMethod();
        writeMethod.invoke(user, "lisi");

        System.out.println(user.getName());

结果:

zhangsan
lisi

 

如果属性不存在会报错如下:

Exception in thread "main" java.beans.IntrospectionException: Method not found: isNamess
at java.beans.PropertyDescriptor.<init>(PropertyDescriptor.java:107)
at java.beans.PropertyDescriptor.<init>(PropertyDescriptor.java:71)
at cn.qlq.Client.main(Client.java:14)

(5)  MethodDescriptor 方法描述器,可以获取方法的名称、Method等信息

其获取方式可以通过BeanInfo获取

        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass(), Object.class);

        // 获取MethodDescriptor描述器
        MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
        for (MethodDescriptor methodDescriptor : methodDescriptors) {
            System.out.println(methodDescriptor);
            
            Method method = methodDescriptor.getMethod();
        }

3.  内省的应用

  采用内省实现的JavaBean转Map和List<Bean>转List<Map>、Map转Bean、Maps转Beans、实现将1个bean的属性赋值给另1个bean(属性拷贝)

package cn.qs.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;

public class BeanUtils {

    /**
     * 内省进行数据转换-javaBean转map
     * 
     * @param obj
     *            需要转换的bean
     * @return 转换完成的map
     * @throws Exception
     */
    public static <T> Map<String, Object> beanToMap(T obj, boolean putIfNull) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 获取javaBean的BeanInfo对象
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass(), Object.class);
        // 获取属性描述器
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            // 获取属性名
            String key = propertyDescriptor.getName();
            // 获取该属性的值
            Method readMethod = propertyDescriptor.getReadMethod();
            // 通过反射来调用javaBean定义的getName()方法
            Object value = readMethod.invoke(obj);

            if (value == null && !putIfNull) {
                continue;
            }

            map.put(key, value);
        }

        return map;
    }

    public static <T> List<Map<String, Object>> beansToMaps(List<T> objs, boolean putIfNull) throws Exception {
        return beansToMaps(objs, putIfNull, false);
    }

    public static <T> List<Map<String, Object>> beansToMaps(List<T> objs, boolean putIfNull, boolean addIndex)
            throws Exception {

        List<Map<String, Object>> result = new ArrayList<>();

        Map<String, Object> beanToMap = null;
        int index = 0;
        for (Object obj : objs) {
            beanToMap = beanToMap(obj, putIfNull);
            if (addIndex) {
                beanToMap.put("index", ++index);
            }

            result.add(beanToMap);
        }

        return result;
    }

    /**
     * Map转bean
     * 
     * @param map
     *            map
     * @param clz
     *            被转换的类字节码对象
     * @return
     * @throws Exception
     */
    public static <T> T map2Bean(Map<String, Object> map, Class<T> clz) throws Exception {
        // new 出一个对象
        T obj = clz.newInstance();
        // 获取person类的BeanInfo对象
        BeanInfo beanInfo = Introspector.getBeanInfo(clz, Object.class);
        // 获取属性描述器
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            // 获取属性名
            String key = propertyDescriptor.getName();
            Object value = map.get(key);

            // 通过反射来调用Person的定义的setName()方法
            Method writeMethod = propertyDescriptor.getWriteMethod();
            writeMethod.invoke(obj, value);
        }
        return obj;
    }

    public static <T> List<T> maps2Beans(List<Map<String, Object>> maps, Class<T> clz) throws Exception {
        List<T> result = new ArrayList<>();
        for (Map<String, Object> map : maps) {
            result.add(map2Bean(map, clz));
        }

        return result;
    }

    /**
     * 复制origin的值到dest上
     * 
     * @param dest
     *            目标对象
     * @param origin
     *            元对象
     * @param setNull
     *            如果源对象属性为null是否拷贝
     * @param excludeFieldNames
     *            排除的属性
     */
    public static <T> void copyProperties(T dest, T origin, boolean setNull, String[] excludeFieldNames) {
        try {
            // 获取person类的BeanInfo对象
            BeanInfo destBeanInfo = Introspector.getBeanInfo(dest.getClass(), Object.class);

            // 获取目标属性描述器
            PropertyDescriptor[] destBeanInfoPropertyDescriptors = destBeanInfo.getPropertyDescriptors();

            for (PropertyDescriptor propertyDescriptor : destBeanInfoPropertyDescriptors) {
                // 获取属性名
                String key = propertyDescriptor.getName();
                if (ArrayUtils.contains(excludeFieldNames, key)) {
                    continue;
                }

                // 获取该属性的值
                Method readMethod = propertyDescriptor.getReadMethod();

                // 如果源对象没有对应属性就跳过
                Object srcValue = null;
                try {
                    srcValue = readMethod.invoke(origin);
                } catch (Exception ignored) {
                    // ignored
                    continue;
                }

                // 如果源对象的值null且null不设置的时候跳过
                if (srcValue == null && !setNull) {
                    continue;
                }

                // 获取setter方法修改属性
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(dest, srcValue);
            }
        } catch (Exception ignored) {
            // ignored
        }
    }

    public static <T> void copyProperties(T dest, T origin) {
        copyProperties(dest, origin, false, null);
    }
}

 4. PropertyEditor

  java.beans.PropertyEditor 属性编辑器位于jre中rt.lib 中。用于类型转换,可以理解为一个封装好的类型转换类。

1. 简单使用如下:

package pt;

import lombok.Data;

@Data
public class MyUser {

    private String username;

    private int age;
}

定义自己的转换器:

package pt;

import java.awt.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyEditor;

public class MyUserPropertyEditor implements PropertyEditor {

    private String text;

    private Object value;

    public MyUserPropertyEditor() {
        System.out.println("pt.MyUserPropertyEditor.MyUserPropertyEditor");
    }

    @Override
    public void setValue(Object value) {
        this.value = value;
    }

    @Override
    public Object getValue() {
        MyUser myUser = new MyUser();
        String[] split = this.text.split("-");
        myUser.setAge(Integer.valueOf(split[1]));
        myUser.setUsername(split[0]);
        return myUser;
    }

    @Override
    public boolean isPaintable() {
        return false;
    }

    @Override
    public void paintValue(Graphics gfx, Rectangle box) {

    }

    @Override
    public String getJavaInitializationString() {
        System.out.println("pt.MyUserPropertyEditor.getJavaInitializationString");
        return null;
    }

    @Override
    public String getAsText() {
        return text;
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        this.text = text;
    }

    @Override
    public String[] getTags() {
        return new String[0];
    }

    @Override
    public Component getCustomEditor() {
        return null;
    }

    @Override
    public boolean supportsCustomEditor() {
        return false;
    }

    @Override
    public void addPropertyChangeListener(PropertyChangeListener listener) {

    }

    @Override
    public void removePropertyChangeListener(PropertyChangeListener listener) {

    }
}

测试如下:

package pt;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;

public class Client2 {

    public static void main(String[] args) {
        PropertyEditorManager.registerEditor(MyUser.class, MyUserPropertyEditor.class);
        // 每次调用的时候会到缓存map 找,然后反射创建对象
        PropertyEditor editor = PropertyEditorManager.findEditor(MyUser.class);
        editor.setValue("user1-25");
        editor.setAsText("usertext1-225");
        System.out.println(editor.getAsText());
        System.out.println(editor.getValue());
        PropertyEditor editor2 = PropertyEditorManager.findEditor(MyUser.class);
        System.out.println(editor2.getAsText());
    }
}

结果:

pt.MyUserPropertyEditor.MyUserPropertyEditor
usertext1-225
MyUser(username=usertext1, age=225)
pt.MyUserPropertyEditor.MyUserPropertyEditor
null

debug 发现,我们注册以及查找的时候是从缓存查找的:com.sun.beans.finder.PropertyEditorFinder#find 源码如下:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.sun.beans.finder;

import com.sun.beans.WeakCache;
import com.sun.beans.editors.BooleanEditor;
import com.sun.beans.editors.ByteEditor;
import com.sun.beans.editors.DoubleEditor;
import com.sun.beans.editors.EnumEditor;
import com.sun.beans.editors.FloatEditor;
import com.sun.beans.editors.IntegerEditor;
import com.sun.beans.editors.LongEditor;
import com.sun.beans.editors.ShortEditor;
import java.beans.PropertyEditor;

public final class PropertyEditorFinder extends InstanceFinder<PropertyEditor> {
    private static final String DEFAULT = "sun.beans.editors";
    private static final String DEFAULT_NEW = "com.sun.beans.editors";
    private final WeakCache<Class<?>, Class<?>> registry = new WeakCache();

    public PropertyEditorFinder() {
        super(PropertyEditor.class, false, "Editor", new String[]{"sun.beans.editors"});
        this.registry.put(Byte.TYPE, ByteEditor.class);
        this.registry.put(Short.TYPE, ShortEditor.class);
        this.registry.put(Integer.TYPE, IntegerEditor.class);
        this.registry.put(Long.TYPE, LongEditor.class);
        this.registry.put(Boolean.TYPE, BooleanEditor.class);
        this.registry.put(Float.TYPE, FloatEditor.class);
        this.registry.put(Double.TYPE, DoubleEditor.class);
    }

    public void register(Class<?> var1, Class<?> var2) {
        synchronized(this.registry) {
            this.registry.put(var1, var2);
        }
    }

    public PropertyEditor find(Class<?> var1) {
        Class var2;
        synchronized(this.registry) {
            var2 = (Class)this.registry.get(var1);
        }

        Object var3 = (PropertyEditor)this.instantiate(var2, (String)null);
        if (var3 == null) {
            var3 = (PropertyEditor)super.find(var1);
            if (var3 == null && null != var1.getEnumConstants()) {
                var3 = new EnumEditor(var1);
            }
        }

        return (PropertyEditor)var3;
    }

    protected PropertyEditor instantiate(Class<?> var1, String var2, String var3) {
        return (PropertyEditor)super.instantiate(var1, "sun.beans.editors".equals(var2) ? "com.sun.beans.editors" : var2, var3);
    }
}

  可以看到find 是从缓存中查找,查找到之后反射创建类实例。

2. JVM 提供了一个java.beans.PropertyEditorSupport, 我们可以选择该类并实现相关方法

(0) java.beans.PropertyEditorSupport 源码如下:

/*
 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.beans;

import java.beans.*;

/**
 * This is a support class to help build property editors.
 * <p>
 * It can be used either as a base class or as a delegate.
 */

public class PropertyEditorSupport implements PropertyEditor {

    /**
     * Constructs a <code>PropertyEditorSupport</code> object.
     *
     * @since 1.5
     */
    public PropertyEditorSupport() {
        setSource(this);
    }

    /**
     * Constructs a <code>PropertyEditorSupport</code> object.
     *
     * @param source the source used for event firing
     * @since 1.5
     */
    public PropertyEditorSupport(Object source) {
        if (source == null) {
           throw new NullPointerException();
        }
        setSource(source);
    }

    /**
     * Returns the bean that is used as the
     * source of events. If the source has not
     * been explicitly set then this instance of
     * <code>PropertyEditorSupport</code> is returned.
     *
     * @return the source object or this instance
     * @since 1.5
     */
    public Object getSource() {
        return source;
    }

    /**
     * Sets the source bean.
     * <p>
     * The source bean is used as the source of events
     * for the property changes. This source should be used for information
     * purposes only and should not be modified by the PropertyEditor.
     *
     * @param source source object to be used for events
     * @since 1.5
     */
    public void setSource(Object source) {
        this.source = source;
    }

    /**
     * Set (or change) the object that is to be edited.
     *
     * @param value The new target object to be edited.  Note that this
     *     object should not be modified by the PropertyEditor, rather
     *     the PropertyEditor should create a new object to hold any
     *     modified value.
     */
    public void setValue(Object value) {
        this.value = value;
        firePropertyChange();
    }

    /**
     * Gets the value of the property.
     *
     * @return The value of the property.
     */
    public Object getValue() {
        return value;
    }

    //----------------------------------------------------------------------

    /**
     * Determines whether the class will honor the paintValue method.
     *
     * @return  True if the class will honor the paintValue method.
     */

    public boolean isPaintable() {
        return false;
    }

    /**
     * Paint a representation of the value into a given area of screen
     * real estate.  Note that the propertyEditor is responsible for doing
     * its own clipping so that it fits into the given rectangle.
     * <p>
     * If the PropertyEditor doesn't honor paint requests (see isPaintable)
     * this method should be a silent noop.
     *
     * @param gfx  Graphics object to paint into.
     * @param box  Rectangle within graphics object into which we should paint.
     */
    public void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box) {
    }

    //----------------------------------------------------------------------

    /**
     * This method is intended for use when generating Java code to set
     * the value of the property.  It should return a fragment of Java code
     * that can be used to initialize a variable with the current property
     * value.
     * <p>
     * Example results are "2", "new Color(127,127,34)", "Color.orange", etc.
     *
     * @return A fragment of Java code representing an initializer for the
     *          current value.
     */
    public String getJavaInitializationString() {
        return "???";
    }

    //----------------------------------------------------------------------

    /**
     * Gets the property value as a string suitable for presentation
     * to a human to edit.
     *
     * @return The property value as a string suitable for presentation
     *       to a human to edit.
     * <p>   Returns null if the value can't be expressed as a string.
     * <p>   If a non-null value is returned, then the PropertyEditor should
     *       be prepared to parse that string back in setAsText().
     */
    public String getAsText() {
        return (this.value != null)
                ? this.value.toString()
                : null;
    }

    /**
     * Sets the property value by parsing a given String.  May raise
     * java.lang.IllegalArgumentException if either the String is
     * badly formatted or if this kind of property can't be expressed
     * as text.
     *
     * @param text  The string to be parsed.
     */
    public void setAsText(String text) throws java.lang.IllegalArgumentException {
        if (value instanceof String) {
            setValue(text);
            return;
        }
        throw new java.lang.IllegalArgumentException(text);
    }

    //----------------------------------------------------------------------

    /**
     * If the property value must be one of a set of known tagged values,
     * then this method should return an array of the tag values.  This can
     * be used to represent (for example) enum values.  If a PropertyEditor
     * supports tags, then it should support the use of setAsText with
     * a tag value as a way of setting the value.
     *
     * @return The tag values for this property.  May be null if this
     *   property cannot be represented as a tagged value.
     *
     */
    public String[] getTags() {
        return null;
    }

    //----------------------------------------------------------------------

    /**
     * A PropertyEditor may chose to make available a full custom Component
     * that edits its property value.  It is the responsibility of the
     * PropertyEditor to hook itself up to its editor Component itself and
     * to report property value changes by firing a PropertyChange event.
     * <P>
     * The higher-level code that calls getCustomEditor may either embed
     * the Component in some larger property sheet, or it may put it in
     * its own individual dialog, or ...
     *
     * @return A java.awt.Component that will allow a human to directly
     *      edit the current property value.  May be null if this is
     *      not supported.
     */

    public java.awt.Component getCustomEditor() {
        return null;
    }

    /**
     * Determines whether the propertyEditor can provide a custom editor.
     *
     * @return  True if the propertyEditor can provide a custom editor.
     */
    public boolean supportsCustomEditor() {
        return false;
    }

    //----------------------------------------------------------------------

    /**
     * Adds a listener for the value change.
     * When the property editor changes its value
     * it should fire a {@link PropertyChangeEvent}
     * on all registered {@link PropertyChangeListener}s,
     * specifying the {@code null} value for the property name.
     * If the source property is set,
     * it should be used as the source of the event.
     * <p>
     * The same listener object may be added more than once,
     * and will be called as many times as it is added.
     * If {@code listener} is {@code null},
     * no exception is thrown and no action is taken.
     *
     * @param listener  the {@link PropertyChangeListener} to add
     */
    public synchronized void addPropertyChangeListener(
                                PropertyChangeListener listener) {
        if (listeners == null) {
            listeners = new java.util.Vector<>();
        }
        listeners.addElement(listener);
    }

    /**
     * Removes a listener for the value change.
     * <p>
     * If the same listener was added more than once,
     * it will be notified one less time after being removed.
     * If {@code listener} is {@code null}, or was never added,
     * no exception is thrown and no action is taken.
     *
     * @param listener  the {@link PropertyChangeListener} to remove
     */
    public synchronized void removePropertyChangeListener(
                                PropertyChangeListener listener) {
        if (listeners == null) {
            return;
        }
        listeners.removeElement(listener);
    }

    /**
     * Report that we have been modified to any interested listeners.
     */
    public void firePropertyChange() {
        java.util.Vector<PropertyChangeListener> targets;
        synchronized (this) {
            if (listeners == null) {
                return;
            }
            targets = unsafeClone(listeners);
        }
        // Tell our listeners that "everything" has changed.
        PropertyChangeEvent evt = new PropertyChangeEvent(source, null, null, null);

        for (int i = 0; i < targets.size(); i++) {
            PropertyChangeListener target = targets.elementAt(i);
            target.propertyChange(evt);
        }
    }

    @SuppressWarnings("unchecked")
    private <T> java.util.Vector<T> unsafeClone(java.util.Vector<T> v) {
        return (java.util.Vector<T>)v.clone();
    }

    //----------------------------------------------------------------------

    private Object value;
    private Object source;
    private java.util.Vector<PropertyChangeListener> listeners;
}
View Code

(1)查看JVM的实现 com.sun.beans.editors.IntegerEditor

package com.sun.beans.editors;

public class IntegerEditor extends NumberEditor {
    public IntegerEditor() {
    }

    public void setAsText(String var1) throws IllegalArgumentException {
        this.setValue(var1 == null ? null : Integer.decode(var1));
    }
}


package com.sun.beans.editors; import java.beans.PropertyEditorSupport; public abstract class NumberEditor extends PropertyEditorSupport { public NumberEditor() { } public String getJavaInitializationString() { Object var1 = this.getValue(); return var1 != null ? var1.toString() : "null"; } }

(2) 编写自己的类

package pt;

import java.beans.PropertyEditorSupport;

public class MyPrt extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        MyUser myUser = new MyUser();
        String[] split = text.split("-");
        myUser.setAge(Integer.valueOf(split[1]));
        myUser.setUsername(split[0]);
        this.setValue(myUser);
    }
}

(3) 测试:

package pt;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;

public class Client2 {

    public static void main(String[] args) {
        PropertyEditorManager.registerEditor(MyUser.class, MyPrt.class);
        // 每次调用的时候会到缓存map 找,然后反射创建对象
        PropertyEditor editor = PropertyEditorManager.findEditor(MyUser.class);
        editor.setAsText("usertext1-225");
        System.out.println(editor.getAsText());
        System.out.println(editor.getValue());
        PropertyEditor editor2 = PropertyEditorManager.findEditor(MyUser.class);
        System.out.println(editor2.getAsText());
    }
}

结果:

MyUser(username=usertext1, age=225)
MyUser(username=usertext1, age=225)
null

 

 

总结:

  如果通过BeanInfo操作属性的话,一般需要过滤掉Object继承的东西,也就是获取BeanInfo的时候如下:

        BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass(), Object.class);

 

关于反射的使用参考: https://www.cnblogs.com/qlqwjy/p/7551550.html

 

posted @ 2019-07-03 22:39  QiaoZhi  阅读(1207)  评论(0编辑  收藏  举报