2012-04-16 91 views
0

考慮以下代碼:可以使用getClass()方法來訪問靜態變量嗎?

class A { 
    static int i=3; 
} 

public class TT extends A { 
    public static void main(String[] args) { 
     System.out.println(new A().getClass().i); 
    } 
} 

能否getClass()方法被用來訪問在這種情況下靜態變量?

+2

只需使用A.I以獲取靜態成員。 – 2012-04-16 18:51:02

回答

9

不是那樣的,沒有。 getClass()返回Class<?>,和i不是Class成員。你可以使用getClass()其次是反射獲取字段的值,但它不是完全清楚你想要什麼在這裏實現 - 當在例子中,你已經給了(這是所有我們已經得到了通過去)簡單地使用A.i會更簡單和更清晰。

0

也許這代碼回答你的問題:

package com.cc.test; 
import java.lang.reflect.Field; 
public class TestMain { 

    public static void main(String[] args) throws Exception { 
     Class theClass = Class.forName("com.cc.test.TestMain$MyClass"); 
     Field theField = theClass.getField("myField"); 
     int theValue = theField.getInt(null); // null only works if myField is static 
     System.out.println(theValue); // prints 99 
    } 

    private static class MyClass { 
     public static int myField = 99; 
    } 
} 
相關問題