簡體   English   中英

按ID設置字段?

[英]Setting a field by id?

我從網絡接收對象。

我需要設置特定字段的值。 但是,我想避免每次使用反射來查找字段。

理想情況下,我想做的事情如下:

int fieldNo = Something.getFieldID("numStairs",SomeClass.class); //do this only once
SomeClass s = (SomeClass)myObject;
s.setField(fieldNo,null);

基本上,首先,我查找我需要的字段的id,然后我設置值,而不必每次都動態執行反射來訪問字段。

我想知道在Java中是否可以使用這樣的東西。

如果沒有,給定一個fieldName字符串和一個Object(斷言該字段確實存在)可能是一種有效的方法,將該字段的值設置為null(假設您也知道該字段可以為空)。

我的版本如下。

SomeClass的

public class SomeClass {

    private Integer numStairs;

    public SomeClass(Integer numStairs) {
        this.numStairs = numStairs;
    }

    public Integer getNumStairs() {
        return numStairs;
    }
}

主要

public class Main {

    private static final Map<Class, Field> cache = new HashMap<>();

    public static void main(String[] args) {
        SomeClass x = new SomeClass(12345);
        //Testing speed
        System.out.println("Test 1");
        int repeats = 10000000;
        long count = 0;
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < repeats; i++) {
            setField(x, i);
            if (x.getNumStairs() == i) {
                count++;
            }
        }
        long t2 = System.currentTimeMillis();
        System.out.println("\tCount = " + count);
        System.out.println("\tTime = " + (t2 - t1));
        System.out.println("Test 2");
        count = 0;
        t1 = System.currentTimeMillis();
        for (int i = 0; i < repeats; i++) {
            setField2(x, i);
            if (x.getNumStairs() == i) {
                count++;
            }
        }
        t2 = System.currentTimeMillis();
        System.out.println("\tCount = " + count);
        System.out.println("\tTime = " + (t2 - t1));
    }

    public static void setField(Object o, Integer value) {
        try {
            Field f = o.getClass().getDeclaredField("numStairs");
            f.setAccessible(true);
            f.set(o, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setField2(Object o, Integer value) {
        try {
            Field f = cache.get(o.getClass());
            if (f == null) {
                f = o.getClass().getDeclaredField("numStairs");
                f.setAccessible(true);
                cache.put(o.getClass(), f);
            }
            f.set(o, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

輸出:

Test 1
    Count = 10000000
    Time = 4092
Test 2
    Count = 10000000
    Time = 1003

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM