XanderYe的个人小站

通过反射查找get/set方法

/**
     * 反射查找get方法
     *
     * @param o
     * @param fieldName
     * @return
     */
    public static Object invokeGet(Object o, String fieldName) {
        Method method = getGetMethod(o.getClass(), fieldName);
        try {
            return method.invoke(o, new Object[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 反射查找set方法
     *
     * @param o
     * @param fieldName
     * @param value
     */
    public static void invokeSet(Object o, String fieldName, Object value) {
        Method method = getSetMethod(o.getClass(), fieldName);
        try {
            method.invoke(o, new Object[]{value});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Method getGetMethod(Class objectClass, String fieldName) {
        StringBuilder sb = new StringBuilder();
        sb.append("get");
        sb.append(fieldName.substring(0, 1).toUpperCase());
        sb.append(fieldName.substring(1));
        try {
            return objectClass.getMethod(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Method getSetMethod(Class objectClass, String fieldName) {
        try {
            Class parameter;
            Field field = objectClass.getDeclaredField(fieldName);
            parameter = field.getType();
            StringBuffer sb = new StringBuffer();
            sb.append("set");
            sb.append(fieldName.substring(0, 1).toUpperCase());
            sb.append(fieldName.substring(1));
            Method method = objectClass.getMethod(sb.toString(), parameter);
            return method;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
赞赏

发表评论

textsms
account_circle
email

XanderYe的个人小站

通过反射查找get/set方法
/** * 反射查找get方法 * * @param o * @param fieldName * @return */ public static Object invokeGet(Object o, String fieldName) { Meth…
扫描二维码继续阅读
2019-01-02