java 反射使用

package com.mycompany.helloworld.refect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 利用反射进行方法调用
 * Createy by user on 7/19/2018.17:57
 */
public class Demo {

    public static void main(String[] args) throws Exception {
        Class clazz = User.class;
        Object obj = clazz.newInstance();
        User u = new User("小明");
        // getDeclaredFields 得到字段
        for (Field f : clazz.getDeclaredFields()) {
            // 当isAccessible()的结果是false时不允许通过反射访问该字段
            f.setAccessible(true);
            System.out.println(f.getName() + ":" + f.get(u));
        }

        // 设置动态调用的方法 设置动态调用的方法的参数是string类型
        Method uriMethod = clazz.getMethod("sayHel", String.class);
        // 动态调用方法
        uriMethod.invoke(obj, "这是应用中的打印");
    }

    public static class User {
        private String name;
        private Integer age;

        public User() {
        }
        public User(String name) {
            this.name = name;
        }
        public void sayHel(String desc) {
            System.out.println("come --->" + desc);
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
    }
}
------------------------------------------------------------
package com.mycompany.helloworld.refect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class CommonServlet {

    private static final Map<String, String> HEADER_FIELD_RELATETION = new HashMap<String, String>();

    static {
        HEADER_FIELD_RELATETION.put("Content-Type", "setContent_type");
        HEADER_FIELD_RELATETION.put("Accept-Language", "setAccept_language");
        HEADER_FIELD_RELATETION.put("Cookie", "setCookie");
        HEADER_FIELD_RELATETION.put("Origin", "setOrigin");
        HEADER_FIELD_RELATETION.put("Locale", "setLocale");
        HEADER_FIELD_RELATETION.put("Host", "setHost");
        HEADER_FIELD_RELATETION.put("Authorization", "setAuthorization");
    }

    private MetaObject messageHeader = new MetaObject();

    public static void main(String[] args) throws Exception {
        System.out.println("refect------start");
        fillImixObjectHeader(new CommonServlet());
    }


    /**
     * HttpServletRequest 转化为MetaObject  利用反射
     * @param requestMessage
     */
    private static void fillImixObjectHeader(CommonServlet requestMessage) throws Exception {
        try {
            /**
             * 取得 CommonRequest类中的 messageHeader字段
             */
            Field headerField = requestMessage.getClass().getDeclaredField("messageHeader");
            // 当isAccessible()的结果是false时不允许通过反射访问该字段
            headerField.setAccessible(true);
            //得到反射字段为Object 反射调用方法时使用
            Object header = headerField.get(requestMessage);
            // 得到反射字段的类型 用来 获取动态调用的方法
            Class<?> headerCls = headerField.getType();

            /**
             * 利用反射动态调用类MessageHeader里面的方法
             */

            for (Map.Entry<String, String> relatetion : HEADER_FIELD_RELATETION.entrySet()) {
                String value = relatetion.getKey();
                if (value != null && !value.trim().equals("")) {
                    // 设置动态调用的方法 设置动态调用的方法的参数是string类型
                    Method headItemMethod = headerCls.getMethod(relatetion.getValue(), String.class);
                    headItemMethod.invoke(header, value); // 动态调用

                }
            }

            // 动态调用 MessageHeader类里面的setUri方法,设置动态调用的方法的参数是string类型
            Method uriMethod = headerCls.getMethod("setUri", String.class);
            uriMethod.invoke(header, "http://localhost:8080/tbs");

            // 动态调用 MessageHeader类里面的的setMethod 方法
            Method methodMethod = headerCls.getMethod("setMethod", String.class);
            methodMethod.invoke(header, "GET");
            headerField.set(requestMessage, header);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class MetaObject {
        private String Method;
        private String authorization;
        private String host;
        private String locale;
        private String cookie;
        private String accept_language;
        private String content_type;
        private String Origin;

        public void setUri(String uri) {
            System.out.println("setUri : " + uri);
        }
        public void setMethod(String method) {
            System.out.println("setMethod:" + method);
        }
        public void setAuthorization(String var1) {
            System.out.println("setAuthorization :" + var1 );
            this.authorization = var1;
        }
        public void setHost(String host) {
            System.out.println("setHost:" +  host);
            this.host = host;
        }
        public void setLocale(String locale) {
            System.out.println("setLocale:" + locale);
            this.locale = locale;
        }
        public void setCookie(String cookie) {
            System.out.println("setCookie:" + cookie);
            this.cookie = cookie;
        }
        public void setAccept_language(String accept_language) {
            System.out.println("setAccept_language:" + accept_language);
            this.accept_language = accept_language;
        }
        public void setContent_type(String content_type) {
            System.out.println("setContent_type:" + content_type);
            this.content_type = content_type;
        }
        public void setOrigin(String origin) {
            System.out.println("setOrigin : " + origin);
            this.Origin = origin;
        }
    }

}

猜你喜欢

转载自www.cnblogs.com/xiaolei2017/p/9349830.html