通过反射机制,程序员可以更加深入的控制程序的执行过程,如在程序运行时对用户输入的信息进行验证,还可以逆向控制程序的执行过程。
Class类与Java反射
通过Java反射机制,可以在程序中访问到已经装在到JVM中的Java对象描述,实现访问、检测、和修改描述Java对象本身信息的功能。
所有的Java类中都继承了Object类,Object类中定义了一个getClass()方法,该方法返回为一个类型为Class类的对象,例:
Class textFieldC = textField.getClass() ;
//利用Java类的对象textFieldC(),可以用来访问该对象的textField对象的描述信息。
访问构造方法
//访问构造方法时,将返回Constructor类型的对象或是数组,每个Constructor对象代表一个构造方法
//一下案例:编写Example_02类,在该类中声明一个String类型成员变量和3个int类型成员变量,并构造3个方法。编写测试类Mian_02,在该类中通过反射访问Example_02类中所有的构造方法,并且将该构造方法是否带有可变数量的参数,入口参数的类型,和可能抛出的异常信息输出到控制台上。
package 反射;
public class Example_02 {
String s;
int i,i2,i3;
private Example_02(){
}
protected Example_02(String s,int i){
this.s=s;
this.i=i;
}
public Example_02(String...strings) throws NumberFormatException {
if (0 < strings.length) {
i = Integer.valueOf(strings[0]);
}
if (1 < strings.length) {
i2 = Integer.valueOf(strings[1]);
}
if (2 < strings.length) {
i3 = Integer.valueOf(strings[2]);
}
}
public void print() {
System.out.println("s="+s);
System.out.println("i="+i);
System.out.println("i2="+i2);
System.out.println("i3="+i3);
}
}
package 反射;
import java.lang.reflect.Constructor;
public class Main_02 {
public static void main(String args[]) {
Example_02 example = new Example_02("10","20","30");
Class<? extends Example_02> exampleC = example.getClass();
//获得所有构造方法
Constructor declaredConstructor[] = exampleC.getDeclaredConstructors();
//遍历构造方法
for (int i = 0 ; i < declaredConstructor.length ; i++) {
Constructor<?> constructor = declaredConstructor[i];
System.out.println("查看是否有可变类型参数:"+ constructor.isVarArgs());
//获取入口参数类型
System.out.println("该构造方法入口参数类型为:");
Class parameterType[] = constructor.getParameterTypes();
for (i = 0 ; i < parameterType.length ; i++) {
System.out.println(parameterType[i]);
}
System.out.println("该构造方法可能抛出的异常类型为:");
//获取异常信息
Class exceptionType[] = constructor.getExceptionTypes();
for (i = 0 ; i < exceptionType.length ; i++) {
System.out.println(exceptionType[i]);
}
Example_02 example2 = null;
while (example2 != null) {
try {
//如果该成员变量的访问权限为private则抛出异常,即不允许访问
if (i == 2) {
//通过执行默认没有参数的构造方法创建对象
example2 = (Example_02) constructor.newInstance();
}
else if (i==1) {
//通过执行具有俩个参数的构造方法创建对象
example2 = (Example_02) constructor.newInstance("7",5);
}
else {
//通过执行具有可变参数的构造方法创建对象
Object parameters[] = new Object[] {new String[] {"100","200","300"}};
example2 = (Example_02) constructor.newInstance(parameterType);
}
} catch (Exception e) {
System.out.println("创建对象时抛出异常,下面执行setAccessible()方法");
//设置为允许访问
constructor.setAccessible(true);
}
}
if (example2 != null) {
example2.print();
System.out.println();
}
}
}
}
访问成员变量
访问成员变量时,将返回Field类型的对象或数组,每一个Field变量代表一个成员变量。
package 反射;
public class Example_03 {
int i;
public float f;
protected boolean b;
private String s;
}
package 反射;
import java.lang.reflect.Field;
public class Main_03 {
public static void main(String args[]) {
Example_03 example = new Example_03();
Class exampleC = example.getClass();
//获取所有的成员变量
Field declaredFields[] = exampleC.getDeclaredFields();
//遍历成员变量
for (int i = 0; i < declaredFields.length; i++) {
Field field1 = declaredFields[i];
//获取成员变量名称
System.out.println("成员变量名为:"+field1.getName());
//获取成员变量类型
Class field1Type = field1.getType();
System.out.println("成员变量类型为:"+field1Type);
boolean isTrue = true;
while (isTrue) {
//如果该成员变量访问权限为private,则抛出异常,即不允许访问
try {
isTrue = false;
//获取成员变量值
System.out.println("修改前的成员变量值为:" + field1.get(example));
//判断成员变量类值类型是否为int类型
if (field1Type.equals(int.class)) {
System.out.println("利用方法setInt()修改成员变量值");
field1.setInt(example,168);
//判断成员变量值是否为float类型
} else if (field1Type.equals(float.class)) {
System.out.println("利用setFloat()方法修改成员变量值");
field1.setFloat(example,189.88f);
//判断成员变量类型是否为boolean类型
} else if (field1Type.equals(boolean.class)) {
System.out.println("利用setBoolean()方法修改成员变量的值");
field1.setBoolean(example,true);
} else {
System.out.println("利用set()方法修改成员变量的值");
//利用set()方法修改,可以为各种类型
field1.set(example,"WZL");
}
System.out.println("修改后的成员变量值为:" + field1.get(example));
} catch (Exception e) {
System.out.println("在设置成员变量值时抛出异常。"+
"下面执行setAccessible()方法");
//设置访问允许
field1.setAccessible(true);
isTrue = true;
}
}
//System.out.println();
}
}
}
访问方法
当访问方法时,将返回Method()类型的对象或是数组,每个·Method对象代表一个方法
package 反射;
public class Example_04 {
static void staticMethod(){
System.out.println("执行staticMethod()方法");
}
public int publicMethod(int i) {
System.out.println("执行publicMethod()方法");
return i*100;
}
private String privateMethod(String...strings) {
System.out.println("执行privateMethod()方法");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0 ; i < strings.length ; i++) {
stringBuffer.append(strings[i]);
}
return stringBuffer.toString();
}
}
package 反射;
import java.lang.reflect.Method;
public class Main_04 {
public static void main(String args[]) {
Example_04 example = new Example_04();
Class exampleC = example.getClass();
//获取所有方法
Method declaredMethods[] = exampleC.getDeclaredMethods();
//遍历方法
for (int i = 0; i < declaredMethods.length ; i++) {
Method method = declaredMethods[i];
System.out.println("该方法的名称为:" + method.getName());
System.out.println("是否允许带有可变数量的参数:" + method.isVarArgs());
System.out.println("入口参数类型为:");
//获取所有参数类型
Class parameterTypes[] = method.getParameterTypes();
for (int j = 0; j < parameterTypes.length ; j++) {
System.out.println(parameterTypes[j]);
}
//获取方法的返回值类型
System.out.println("该方法的返回值类型为:" + method.getReturnType());
System.out.println("可能抛出的异常类型与:");
Class exceptionTypes[] = method.getExceptionTypes();
for (int k = 0 ; k < exceptionTypes.length; k ++) {
System.out.println(exceptionTypes[k]);
}
boolean isTrue = true;
while (isTrue) {
//如果该方法的访问全线为private,则抛出异常,即不允许访问
try {
isTrue = false;
if ("staticMethod".equals(method.getName())) {
//执行没有参数入口的方法
method.invoke(example);
}
else if ("publicMethod".equals(method.getName())) {
System.out.println("返回值为:" + method.invoke(example,168));
}
else if ("protectedMethod".equals(method.getName())) {
System.out.println("返回值为:" + method.invoke(example,"7",5));
}
else if ("private".equals(method.getName())) {
Object parameters[] = new Object[]{new String[]{"W","Z","L"}};
System.out.println("返回值为:" + method.invoke(example,parameters));
}
} catch (Exception e) {
System.out.println("在执行方法中抛出异常。"
+ "下面执行setAccessible()方法");
//设置为允许访问
method.setAccessible(true);
isTrue = true;
}
}
}
}
}
//注意:在反射中执行具有可变数量的参数的数组时,需要将入口参数定义为二维数组。
Annotation
//定义Annotation类型的关键字为@interface,这个关键字隐含意思为继承了某个接口
//Annotation类型中可以只包含一个或是多个成员,也可以不包含成员,也可以为成员设置默认值。
//定义元素时可以通过Annotation类型@target来设置适应的元素种类。未设置则适应于所有的程序元素。枚举类中的枚举常量来设置@target
//通过@Retention来设置Annotation的有效范围
ackage 反射;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**首先用来编写一个注释构造方法的Annotation类型,@Constructor_Annotation
* 在有效范围为运行时加载到JVM中
* */
//用于构造方法
@Target(ElementType.CONSTRUCTOR)
//运行时加载到JVM中
@Retention(RetentionPolicy.RUNTIME)
public @interface Construct_Annotation {
//定义一具有默认值的String类型·成员吧变量
String value() default "默认构造方法";
}
/**定义一个用来注释字段,方法和参数的Annotation类型@Field_Method_Parameter_Annotation
* 有效范围为在运行时加载到JVM中
* */
//用于字段方法和参数
@Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER})
//运行时加载到JVM中
@Retention(RetentionPolicy.RUNTIME)
public @interface Field_Method_Parameter_Annotation {
String describe();
Class type() default void.class;
}
public class Record {
//注释字段
@Field_Method_Parameter_Annotation(describe = "编号" , type = int.class)
int id;
@Field_Method_Parameter_Annotation(describe = "姓名" , type = String.class)
String name;
@Construct_Annotation()
//采用默认值注释构造方法
public Record() {
}
@Construct_Annotation("立即初始化构造方法")
public Record(
//注释构造方法
@Field_Method_Parameter_Annotation(describe = "编号" , type = int.class) int id,
@Field_Method_Parameter_Annotation(describe = "姓名" ,type = int.class) String name
) {
this.id = id;
this.name = name;
}
@Field_Method_Parameter_Annotation(describe = "获得编号" , type = int.class)
public int getId() {
//注释方法
return id;
}
@Field_Method_Parameter_Annotation(describe = "设置编号" )
public void setId(
//成员type采用默认值的注释方法
//注释方法的参数
@Field_Method_Parameter_Annotation(describe = "编号" , type = int.class) int id
){
this.id = id;
}
@Field_Method_Parameter_Annotation(describe = "获得姓名" , type = String.class)
public String getName() {
return name;
}
@Field_Method_Parameter_Annotation(describe = "设置姓名")
public void setName(
@Field_Method_Parameter_Annotation(describe = "姓名" , type = String.class) String name1
){
this.name = name;
}
}
个人小结:
当利用反射访问成员变量,方法、构造方法时,需要先实例化类的对象。然后在获取类的名称,进而获取构造方法集合、成员变量集合,再用类中的方法访问即可。Annotation与次类似。