import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* java反射
* 成员变量 Field
* 方法 Method
*
*/
public class T {
public static void main(String[] args) throws Exception {
//成员变量反射
M m = new M(3,5);
Field fieldx = M.class.getDeclaredField("x"); //获取对应字段
fieldx.setAccessible(true); //强制访问 x为private
System.out.println(fieldx.get(m)); //获取字段对应结果
Field fieldy = M.class.getDeclaredField("y"); //获取对应字段
System.out.println(fieldy.get(m)); //获取字段对应结果
System.out.println("-----------反射成员变量---Field-----------------");
changer(m);
System.out.println(m);
System.out.println("-----------反射方法---Method-----------------");
String str= "aa";
System.out.println(str.getClass().getMethods()[1]); //获取所有的方法名称,再通过getMethod获取具体的方法,再通过invoke去调用
Method method = String.class.getMethod("charAt", int.class);
System.out.println( method.invoke(str,1));
System.out.println("----------------用反射调用main方法--------------");
String className = args[0];
Method method1 = Class.forName(className).getMethod("main",String[].class);
method1.invoke(null,new Object[]{new String []{"111","aaa"}});
}
//反射修改成员变量的数值
private static void changer(Object obj) throws Exception {
Field[] fields = obj.getClass().getFields();
for (Field field: fields) {
//System.out.println(field.getType()); //类型
//System.out.println(field.get(obj)); //value
if(field.getType()==String.class){
String oldValue = (String)field.get(obj);
String newValue = oldValue.replaceAll("a","bbbb");
field.set(obj,newValue);
}
}
}
}
class M {
private int x;
public int y;
public String str1 = "ball";
public String str2 = "bnb";
public String str3 = "abd";
public M(int x, int y) {
this.x = x;
this.y = y;
}
public static void main(String[] args) {
for (String a:args
) {
System.out.println(a);
}
}
@Override
public String toString() {
return "M{" +
"x=" + x +
", y=" + y +
", str1='" + str1 + '\'' +
", str2='" + str2 + '\'' +
", str3='" + str3 + '\'' +
'}';
}
}
JAVA反射基础与应用
最新推荐文章于 2024-10-06 20:16:20 发布