获取类的T类型的静态最终字段

时间:2014-05-05 16:18:07

标签: java class static final

我有以下三个类定义:

public class Bounds {
    public Bounds (int a, int b, int c, int d) { /* ... */ }
    /* ... */
}

public class A {
    public static final Bounds BOUNDS = new Bounds(1, 2, 3, 4);

    public A () { /* ... */ }
    /* ... */
}

public class B extends A {
    public static final Bounds BOUNDS = new Bounds(5, 6, 7, 8);

    public B () { super(); /* ... */ }
    /* ... */
}

然后我有一个看起来像这样的方法:

public void Foo (Class<? extends A> cls) {
    cls.getField("BOUNDS").get(null); // Doesn't work
}

当我尝试拨打Foo(B.class)时,我收到一条错误消息&#34;不兼容的类型&#34;同时突出显示get(null)。我的问题是:如何使用 BOUNDS -class? Class 的值>

(我不想知道我可以使用 A 而不是 Class<? extends A>

编辑:如果我使用getInt(null)表示静态最终整数,或getDouble(null)表示静态最终双精度数,则可以正常工作。

1 个答案:

答案 0 :(得分:1)

将方法更改为:

public <T extends A> void Foo (Class<T> cls) {
    System.out.println(cls.getField("BOUNDS").get(null));
}

测试此方法:

class Bounds {
    int a, b, c, d;
    public Bounds (int a, int b, int c, int d) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }
    @Override
    public String toString() {
        return "Bounds [a=" + a + ", b=" + b + ", c=" + c + ", d=" + d + "]";
    }
}

//classes A and B were kept as defined in OP's code

public class Test {

    public static <T extends A> void Foo (Class<T> cls) {
        try {
            System.out.println(cls.getField("BOUNDS").get(null));
        } catch(Exception lazyToHandle) {}
    }
    public static void main(String[] args) throws Exception {
        Foo(B.class);
    }
}

打印:

Bounds [a=5, b=6, c=7, d=8]