Java反射笔记3―变量和方法

2014-11-24 03:16:43 · 作者: · 浏览: 0

Java也可以利用反射得到对应的类中的变量和方法,这个对于在我们使用的时候不知道类的具体情况的时候,对我们很有用。可能因为我学的也不多对于Java的反射机制的具体作用我也不是很清楚,但是我知道一点,可以利用这个机制,在我们无法看清一个类的内部情况的时候,可以得到类的内部情况。

下面我们给出一个例子程序,显示一下反射得到变量和方法是怎么做的,如果哪里不妥,还请指出:

Demo类为了测试所用:

public class Demo

{

public String str1 = "bbbbA";

public String str2 = "abc";

public String str3 = "def";

public Demo(int x, int y)

{

this.x = x;

this.y = y;

}

@Override

public int hashCode()

{

final int prime = 31;

int result = 1;

result = prime * result + x;

result = prime * result + y;

return result;

}

@Override

public boolean equals(Object obj)

{

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

Demo other = (Demo) obj;

if (x != other.x)

return false;

if (y != other.y)

return false;

return true;

}

private int x;

public int y;

@Override

public String toString()

{

return "Demo [x=" + x + ", y=" + y + ", str1=" + str1 + ", str2="

+ str2 + ", str3=" + str3 + "]";

}

public void display(String str)

{

System.out.println(str);

}

}

下面的代码是我们通过反射得到上面类中的变量和方法:

import java.lang.reflect.Field;

import java.lang.reflect.Method;

public class ReflectDemo

{

public static void main(String[] args) throws Exception

{

Demo d = new Demo(3,5);

Field fieldY = d.getClass().getField("y");

//fieldY得到是y变量具体是哪个对象的y变量,必须用下面的方法去取出来,get方法只能得到可见的变量

System.out.println(fieldY.get(d));

Field fieldX = d.getClass().getDeclaredField("x");

//下面的语句是暴利反色,如果不写的话,我们是不能取到private的变量的

fieldX.setAccessible(true);

System.out.println(fieldY.get(d));

System.out.println("改变以前的:"+d);

Field[] fields = d.getClass().getFields();

for(Field field : fields)

{

if(field.getType() == String.class)

{

String oldValue = (String)field.get(d);

String newValue = oldValue.replace('b', 'a');

field.set(d, newValue);

}

}

System.out.println("改变以后的:"+d);

//方法的反色

Method display = Demo.class.getMethod("display", String.class);

//invoke第一个对象是使用哪个对象调用,如果是静态对象,那就直接写null,后面是这个对象调用的方法需要的参数

display.invoke(d, "mengxiangyue");

}

}

下面是上面程序运行的结果:

5

5

改变以前的:Demo [x=3, y=5, str1=bbbbA, str2=abc, str3=def]

改变以后的:Demo [x=3, y=5, str1=aaaaA, str2=aac, str3=def]

mengxiangyue

如果哪里写的不妥,还请指出。

【作者:孟祥月 博客:http://blog.csdn.net/mengxiangyue】