java 反射

来源:互联网 发布:五轴编程工资多少钱 编辑:程序博客网 时间:2024/05/02 00:17

把java类中的各种成分映射成相应的java类。

 

Constructor 构造方法类

 

 以字节码的形式得到类的构造方法,它可以获得所属类,类的修饰符等

 

Constructor的DEMO: 

1,在类字节码上得到一个类的构造方法。

2,用构造方法去创建一个实例对象。

  //StringBuffer.class获得方法时要用到的类型
  Constructor c1=String.class.getConstructor(StringBuffer.class);
  //调用获得的方法时要用相同类型的实例对象。
  String str2=(String)c1.newInstance(new StringBuffer("abc"));
  System.out.println(str2.charAt(1));

 

--------------------------------------------------------------------------------------------------------------------------------------

Field字段类:

1,获取字节码上的变量

2,指定从哪个类获取

 

DEMO:

public class ReflectPoint {
 private int x;
 public int y;
 
 public ReflectPoint(int x, int y) {
  super();
  this.x = x;
  this.y = y;
 }
}

 

 

 ReflectPoint pt1=new ReflectPoint(3,5);
  Field fieldY=pt1.getClass().getField("y");
  //FileldY是字节码类上的变量。要用它去取某个对象上的值。
  System.out.println(fieldY.get(pt1));
  //调用私有的 暴力反射
  Field fieldX=pt1.getClass().getDeclaredField("x");
  fieldX.setAccessible(true);//设为可访问
  System.out.println(fieldX.get(pt1));

 

 

//替换字符

private static void changeStringValue(Object obj) throws Exception{
  Field[] fields=obj.getClass().getFields();
  for (Field field:fields) {
   //只要对字节码比较用==比
   //得到自己的类型,因为字节码只有一份所以用等号更合适
   if(field.getType()==String.class){
    String oldValue=(String)field.get(obj);
    String newValue=oldValue.replace('b', 'a');
    field.set(obj,newValue);
   }
  }
  
 }

 

--------------------------------------------------------------------------------------------------------------------

 

Method类

设置方法格式:

Method methodVar=String.class.getMethod("方法名",参数类型);

调用方法格式:

methodVar.invoke(对象名,参数值);

 

 

 

 

原创粉丝点击