java反射机制
反射机制:在Java环境中,反射机制允许程序在执行时获取某个类自身的定义信息,例如熟悉和方法等也可以实现动态创建;类的对象、变更属性的内容或执行特定的方法的功能。从而使Java具有动态语言的特性,增强了程序的灵活性和可移植性。
作用
- 在运行时判断任意一个对象所属的类型。
- 在运行时构造任意一个类的对象。
- 在运行时判断任意一个类所具有的成员变量和方法。
- 在运行时调用任意一个对象的方法,甚至可以调用private方法。
注意:上述功能都是在运行时环境中,而不是在编译时环境中。
案例代码
//测试类
public class Reflect {
/**
* 获取类方法和类属性
*/
public static void test1(){
Class c = Test.class;
Method[] methods = c.getMethods();
for(int i = 0;i<methods.length;i++){
System.out.println(methods[i].getName());
}
Field[] fields = c.getDeclaredFields();
for(Field f : fields){
System.out.println(f.getType()+":"+f.getName());
}
}
/**
* 根据类名动态创建类的对象
* @throws Exception
*/
public static void test2() {
try {
Class c = Class.forName("反射机制.Test");
Test Test = (Test)c.newInstance();
Test.setI(1);
Test.setJ("1001");
Test.getI();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* 根据类名和方法名,执行对象的方法
* @param
* @param method
* @param value
* @throws Exception
*/
public static void test3(Test test,String method,String value) {
try {
Class c = test.getClass();
Method set = c.getMethod(method,new Class[]{String.class});
set.invoke(test,new Object[]{value});
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 动态创建数组对象,对数组元素复制和取值
*/
public static void test4(){
try{
Class cls = Class.forName("java.lang.String");
//创建一个String类型的数组,大小为10
Object arr = Array.newInstance(cls, 10);
//在数组5索引的位置赋值
Array.set(arr, 5, "this is a test");
//获取数组5索引位置的值
String s = (String) Array.get(arr, 5);
System.out.println(s);
}catch(Throwable e){
System.out.println(e);
}
}
public static void main(String[] args) {
try {
Reflect.test1();
Reflect.test2();
Class c = Class.forName("反射机制.Test");
Test test = (Test)c.newInstance();
Reflect.test3(test ,"printTest","test");
Reflect.test4();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
实体类
public class Test {
private int i = 0;
private String j = "test";
public void mytest(){}
public int mytest(int i){
System.out.println(i);
return i;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getJ() {
return j;
}
public void setJ(String j) {
this.j = j;
}
public void printTest(String test){
System.out.println(test);
}
}