蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 OpenJDK 1.8 JavaBean Introspector 内省、序列化与 useBean/setProperty 反射实测

JAVAWindows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。ExploreJavabean.java
ExploreJavabean.java246 行
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ExploreJavabean {

    public static class StudentsBean implements Serializable {
        private static final long serialVersionUID = 1L;
        private String firstName = null;
        private String lastName = null;
        private int age = 0;
        private String auditTag = "";

        public StudentsBean() {
        }

        public String getFirstName() { return firstName; }
        public String getLastName() { return lastName; }
        public int getAge() { return age; }

        public void setFirstName(String firstName) { this.firstName = firstName; }
        public void setLastName(String lastName) { this.lastName = lastName; }
        public void setAge(int age) { this.age = age; }

        // Read-only derived property (getter only)
        public String getFullName() {
            return (lastName == null ? "" : lastName) + (firstName == null ? "" : firstName);
        }

        // Write-only property (setter only)
        public void setAuditTag(String tag) { this.auditTag = tag; }

        String peekAuditTag() { return auditTag; }
    }

    static class JspBeanRegistry {
        private final Map<String, Map<String, Object>> scopes = new LinkedHashMap<>();

        JspBeanRegistry() {
            scopes.put("page", new LinkedHashMap<>());
            scopes.put("request", new LinkedHashMap<>());
            scopes.put("session", new LinkedHashMap<>());
            scopes.put("application", new LinkedHashMap<>());
        }

        Object useBean(String id, String scope, Class<?> cls) throws Exception {
            Map<String, Object> bag = scopes.get(scope);
            if (!bag.containsKey(id)) {
                bag.put(id, cls.getDeclaredConstructor().newInstance());
            }
            return bag.get(id);
        }

        void setProperty(Object bean, String property, String rawValue) throws Exception {
            BeanInfo info = Introspector.getBeanInfo(bean.getClass(), Object.class);
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                if (pd.getName().equals(property) && pd.getWriteMethod() != null) {
                    Method setter = pd.getWriteMethod();
                    Class<?> paramType = setter.getParameterTypes()[0];
                    Object converted = (paramType == int.class || paramType == Integer.class)
                        ? Integer.parseInt(rawValue)
                        : rawValue;
                    setter.invoke(bean, converted);
                    return;
                }
            }
            throw new IllegalArgumentException("No writable property: " + property);
        }

        Object getProperty(Object bean, String property) throws Exception {
            BeanInfo info = Introspector.getBeanInfo(bean.getClass(), Object.class);
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                if (pd.getName().equals(property) && pd.getReadMethod() != null) {
                    return pd.getReadMethod().invoke(bean);
                }
            }
            throw new IllegalArgumentException("No readable property: " + property);
        }
    }

    public static void main(String[] args) throws Exception {
        List<Map<String, Object>> cases = new ArrayList<>();

        // Case 1: Real java.beans.Introspector property inspection (rw / ro / wo) & Serializable round-trip
        BeanInfo beanInfo = Introspector.getBeanInfo(StudentsBean.class, Object.class);
        Map<String, String> propModes = new LinkedHashMap<>();
        for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
            boolean r = pd.getReadMethod() != null;
            boolean w = pd.getWriteMethod() != null;
            String mode = (r && w) ? "rw" : (r ? "ro" : "wo");
            propModes.put(pd.getName(), mode);
        }

        StudentsBean original = new StudentsBean();
        original.setFirstName("小强");
        original.setLastName("王");
        original.setAge(10);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(original);
        }
        StudentsBean restored;
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
            restored = (StudentsBean) ois.readObject();
        }

        Map<String, Object> introExp = new LinkedHashMap<>();
        introExp.put("age_mode", "rw");
        introExp.put("firstName_mode", "rw");
        introExp.put("lastName_mode", "rw");
        introExp.put("fullName_mode", "ro");
        introExp.put("auditTag_mode", "wo");
        introExp.put("serializable_roundtrip_match", true);

        Map<String, Object> introAct = new LinkedHashMap<>();
        introAct.put("age_mode", propModes.get("age"));
        introAct.put("firstName_mode", propModes.get("firstName"));
        introAct.put("lastName_mode", propModes.get("lastName"));
        introAct.put("fullName_mode", propModes.get("fullName"));
        introAct.put("auditTag_mode", propModes.get("auditTag"));
        introAct.put("serializable_roundtrip_match",
            "小强".equals(restored.getFirstName())
                && "王".equals(restored.getLastName())
                && restored.getAge() == 10);
        addCase(cases, "javabean_introspector_and_serialization",
            "使用 java.beans.Introspector 内省验证可读写/只读/只写属性,并完成 Serializable 序列化往返。",
            introExp, introAct);

        // Case 2: <jsp:useBean> scope lookup & instantiation (java.util.Date & StudentsBean)
        JspBeanRegistry reg = new JspBeanRegistry();
        Date date1 = (Date) reg.useBean("date", "page", Date.class);
        Date date2 = (Date) reg.useBean("date", "page", Date.class);
        StudentsBean sPage = (StudentsBean) reg.useBean("students", "page", StudentsBean.class);
        StudentsBean sSession = (StudentsBean) reg.useBean("students", "session", StudentsBean.class);

        Map<String, Object> scopeExp = new LinkedHashMap<>();
        scopeExp.put("date_is_util_date", true);
        scopeExp.put("same_scope_reuses_instance", true);
        scopeExp.put("different_scopes_isolated", true);

        Map<String, Object> scopeAct = new LinkedHashMap<>();
        scopeAct.put("date_is_util_date", date1 != null && date1.getTime() > 0L);
        scopeAct.put("same_scope_reuses_instance", date1 == date2);
        scopeAct.put("different_scopes_isolated", sPage != sSession);
        addCase(cases, "jsp_usebean_scope_lifecycle",
            "验证 jsp:useBean 按 page/request/session/application 作用域复用同 id 实例并隔离跨作用域实例。",
            scopeExp, scopeAct);

        // Case 3: <jsp:setProperty> & <jsp:getProperty> with String->int type conversion
        reg.setProperty(sPage, "firstName", "小强");
        reg.setProperty(sPage, "lastName", "王");
        reg.setProperty(sPage, "age", "10");
        reg.setProperty(sPage, "auditTag", "verified");

        Map<String, Object> propExp = new LinkedHashMap<>();
        propExp.put("firstName", "小强");
        propExp.put("lastName", "王");
        propExp.put("age", 10);
        propExp.put("fullName", "王小强");
        propExp.put("auditTag_written", "verified");

        Map<String, Object> propAct = new LinkedHashMap<>();
        propAct.put("firstName", reg.getProperty(sPage, "firstName"));
        propAct.put("lastName", reg.getProperty(sPage, "lastName"));
        propAct.put("age", reg.getProperty(sPage, "age"));
        propAct.put("fullName", reg.getProperty(sPage, "fullName"));
        propAct.put("auditTag_written", sPage.peekAuditTag());
        addCase(cases, "jsp_set_and_get_property_reflection",
            "通过 Introspector 反射执行 setProperty(含字符串 \"10\" 自动转 int)与 getProperty 读取全部属性。",
            propExp, propAct);

        Map<String, Object> root = new LinkedHashMap<>();
        root.put("version", "OpenJDK " + System.getProperty("java.version"));
        root.put("cases", cases);
        System.out.println(toJson(root));
    }

    private static void addCase(List<Map<String, Object>> cases, String name, String summary, Object expected, Object actual) {
        Map<String, Object> c = new LinkedHashMap<>();
        c.put("name", name);
        c.put("summary", summary);
        c.put("expected", expected);
        c.put("actual", actual);
        c.put("passed", Objects.equals(expected, actual));
        cases.add(c);
    }

    private static String toJson(Object obj) {
        if (obj == null) return "null";
        if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
        if (obj instanceof String) return escapeString((String) obj);
        if (obj instanceof List<?>) {
            StringBuilder sb = new StringBuilder("[");
            List<?> list = (List<?>) obj;
            for (int i = 0; i < list.size(); i++) {
                if (i > 0) sb.append(",");
                sb.append(toJson(list.get(i)));
            }
            return sb.append("]").toString();
        }
        if (obj instanceof Map<?, ?>) {
            StringBuilder sb = new StringBuilder("{");
            boolean first = true;
            for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
                if (!first) sb.append(",");
                first = false;
                sb.append(escapeString(String.valueOf(e.getKey()))).append(":").append(toJson(e.getValue()));
            }
            return sb.append("}").toString();
        }
        return escapeString(String.valueOf(obj));
    }

    private static String escapeString(String s) {
        StringBuilder sb = new StringBuilder("\"");
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
                case '"': sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (ch < 0x20) sb.append(String.format("\\u%04x", (int) ch));
                    else sb.append(ch);
            }
        }
        return sb.append("\"").toString();
    }
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。

入口文件:projects/jsp-javabean-lab/ExploreJavabean.java

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreJavabean.java,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:JSP

课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202612a1388.zip

下载课程关联工程包:JSP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1407.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习