首页 > 代码库 > jav利用反射修改类的静态变量

jav利用反射修改类的静态变量

有Student这个类:

public class Student {    private static String schoolName="";        private static String schoolArea= "";        private static boolean isSetValue= http://www.mamicode.com/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中默认赋的初始值,

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对象的一个实例

 

jav利用反射修改类的静态变量