jav利用反射修改類的靜態變量

有Student這個類:java

public class Student {
    private static String schoolName="";
    
    private static String schoolArea= "";
    
    private static boolean isSetValue= false;
    
    private String name;
    
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
}

 

如今想將類中的全部靜態變量改成java中默認賦的初始值,this

public static void resetStaticVar()
{

    Field[] fields= Student.class.getDeclaredFields();

    for(Field field:fields)
    {
        if(Modifier.isStatic(field.getModifiers()))
        {
            if(field.getType()==int.class)
            {
                field.set(null,0);
            }
            else if(field.getType()==float.class)
            {
                field.set(null,0.0);
            }
            else if(field.getType()=double.class)
            {
                field.set(null,0.0D);
            }
            else if(field.getType()==boolean.class)
            {
                field.set(null,false);
            }
            else
            {
                Object val= field.getType().newInstance();
                field.set(null,val);
            }
        }
    }

}

或者這裏的null也能夠換成Student對象的一個實例spa

相關文章
相關標籤/搜索