Java 中的反射

反射中的contructor:

            Contructor [] constructors=String.class.getContructors(); 

            fields

           

package cn.itcast.day2;

public class ReflectTest {  public int x;  private int y;  public String str1 = "ball";  public String str2 = "basketball";  public String str3 = "itcast";

 public int getX()  {   return x;  }

 public void setX(int x)  {   this.x = x;  }

 public int getY()  {   return y;  }

 public void setY(int y)  {   this.y = y;  }

 public ReflectTest(int x, int y)  {   this.x = x;   this.y = y;  } }

利用反射修改一个类中类型为string 的字段

private static void changeStringValue() throws IllegalArgumentException, IllegalAccessException
 {
  ReflectTest test = new ReflectTest(5, 6);
  Field[] filField = test.getClass().getFields();
  for (Field field : filField)
  {
   if (field.getType() == String.class)
   {
    System.out.println("原来的值:" + field.get(test));
    field.set(test, field.get(test).toString().replace("a", "b"));
    System.out.println("现在的值:" + field.get(test));
   }
  }
 }

            method

          

           利用反射来操作main方法:

  String[] aragsStrings = { "121", "4545", "fdsf" };
  Method mothedMethod = ConstructorDemo.class.getMethod("main", String[].class);
  mothedMethod.invoke(null,(Object)aragsStrings);
  

posted on 2013-04-29 09:07  peter.peng  阅读(133)  评论(0编辑  收藏  举报