最近写程序用到了一点java反射,拿出来让大家看看~~
====================================
以前做docomo的时候,有时候每个类的东西非常多,所以就是以名字来命名变量,比如我们从百度API里面拿到的一个参数就是 comments 那么我们定义一个变量名字也就是comments
但是这样的内部变量有很多,所以我们在处理的时候需要将所有的名字都重新赋值一遍,这样做很痛苦,所以我就想了一个新办法
private Map<String,String> pullargs()
{
Map<String,String> ParamMap=new HashMap<>();
Field[] fields = this.getClass().getDeclaredFields();
for(int i=0;i<fields.length;i++)
{
Field f = fields[i];
try {
if(f.get(this)!=null)
{
String type = f.getGenericType().toString();
if(type.equals("class java.lang.String"))
{
if(!f.get(this).toString().equals(""))
{
ParamMap.put(f.getName(), f.get(this).toString());
}
}
else if(type.equals("class java.lang.Integer"))
{
ParamMap.put(f.getName(), (int)f.get(this)+"");
}
else if(type.equals("class java.lang.Float"))
{
ParamMap.put(f.getName(), (float)f.get(this)+"");
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
return ParamMap;
}上面这个是我们从这个类里面拿到这个变量,以变量名字为key 值为value来对一个map进行赋值
还有一个是
Field[] fields = this.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
String type = f.getGenericType().toString();
if (type.equals("class java.lang.String")) {
Element temp = element.getElementsByTag(f.getName()).first();
if (temp != null) {
try {
f.set(this, temp.text());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
} else if (type.equals("class java.lang.Integer")) {
Element temp = element.getElementsByTag(f.getName()).first();
if (temp != null) {
int txt = Integer.parseInt(temp.text());
try {
f.set(this, txt);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
这个跟上面的哪一个类型差不多 也就是从一个Element里面拿到东西并且判断是不是这个field里面的 但是我们这里用的是
getDeclaredFields 也就是内部成员变量,要是想要所有变量 就用getFields
========================================================================================
现在我们看看我要把一个类内部静态变量中所有类型为 Integer[] 的数组初始化 改怎么办
Class<?> aClass = this.getClass();
Field[] field=aClass.getFields();//获取全部参数
Arrays.asList(field).forEach(x -> {
int modifier = x.getModifiers();
if (modifier == Modifier.PUBLIC + Modifier.STATIC) {
String type = x.getType().getName();
if (type.equals(Integer[].class.getName())) {
try {
x.set(this,initArray((Integer[]) x.get(this)));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
});private Integer[] initArray(Integer[] array)
{
for (int i = 0; i < array.length; i++) {
array[i]=0;
}
return array;
}
可以看到我们先用getModifier看看是不是public static
然后看看类型是不是什么 在设置的时候 我们要也把这个东西真正的拿出来 用的就是 x.get(this)
我感觉反射的难点主要在怎么把东西从这个类里面拿出来
回复列表: