Loading

Java之反射机制五:反射优化方式之一

一:实体类

package reflex;
public class BigDog extends Dog {
    private Integer age;

    public String name;
    public String name2;
    public String name3;
    public String name4;
    public String name5;
    public String name6;
    public String name7;
    public String name8;
    public String name9;
    public String name10;
    public String name11;
    public String name12;

    public BigDog(){}

    public BigDog(Integer age){
        this.age = age;
    }

    private void getDog(){}

    private BigDog(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    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;
    }

    @Override
    public String toString() {
        return "BigDog{" +
                "age=" + age +
                '}';
    }
}

二:优化方式之一(不明显)

package reflex;

import org.junit.Test;

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

public class ReflectService {
    private static Map<String, Field> fieldMap = new HashMap<>();

    static {
        Field[] fields = BigDog.class.getDeclaredFields();
        Method[] methods = BigDog.class.getDeclaredMethods();
        Arrays.asList(fields).forEach(field -> {
            field.setAccessible(true);
            String str = field.toString();
            String attribute = str.substring(str.lastIndexOf(".")+1);
            fieldMap.put(attribute,field);
        });
    }

    public long test() throws Exception {
        long start = System.currentTimeMillis();
        for(int i = 0;i<100000000;i++){
            BigDog bigDog = new BigDog();
            Field age = bigDog.getClass().getDeclaredField("age");
            age.setAccessible(true);
            age.set(bigDog,1);
        }
        long end = System.currentTimeMillis();
        System.out.println((end-start)+"ms");
        return end-start;
    }

    public long test2() throws Exception {
        long start = System.currentTimeMillis();
        for(int i = 0;i<100000000;i++){
            BigDog bigDog = new BigDog();
            Field age = fieldMap.get("age");
            age.set(bigDog,1);
        }
        long end = System.currentTimeMillis();
        System.out.println((end-start)+"ms");
        return end-start;
    }

    @Test
    public void test3() throws Exception{
        long test = test();
        long test2 = test2();
        System.out.println((test - test2)+"ms");
    }
}

运行结果:

6954ms

1358ms

5596ms

 

 

 

 

 

 

 

posted @ 2020-03-21 22:19  秋风飒飒吹  阅读(550)  评论(0编辑  收藏  举报