java反射性能

項目中用到了java的反射,能夠大大減小代碼量。可是反射的性能卻不容樂觀,作了個簡單的測試,以下。java

 

    public void noreflect() {
        Person p = new Person();
        for(int i=0; i<10000000; ++i){
            Person.setName(p, "name");
            Person.setAge(p, "22");
        }
    }

    @Test
    public void reflect(){
        Person p = new Person();
        try {
            for(int i=0; i<10000000; ++i){
                Method setname = Person.class.getDeclaredMethod("setName", Person.class, String.class);
                Method setage = Person.class.getDeclaredMethod("setAge", Person.class, String.class);

                setname.invoke(null, p, "name");
                setage.invoke(null, p, "22");
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

  

相關文章
相關標籤/搜索