흑마 프로그램--java 반사 실례

3189 단어 java 반사
------------------------------------------- android 교육당신과 교류하기를 기대합니다-----------------------------------------반사:class를java류Constructor구조기1로 비추어 모든 구조방법을 얻다
Constructor[] ctc=Class.forName(“”).contructors();

2. 어떤 구조 방법을 얻다
Constructor  ctc=Class.forName().getConstructor(StringBuffer.class)

3. 객체 만들기
String str=(String)Ctc.newInstance(new StringBuffer(“abc”));

참고: class.newInstance()와 constructor.Instance () 의 차이점: 전자는 무참한 구조 함수로만 실례 대상을 만들 수 있고, 후자는 무참과 유참한 구조 함수로 실례 대상을 만들 수 있습니다 Field: 구성원 함수의 반사
//     
public class ReflectPoint {
private  int x;
public int y;
public String str1="ball";
public String str2="basketball";
public String itcast="itcast";
public ReflectPoint(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) throws Exception{
ReflectPoint r=new ReflectPoint(3, 5);
Field x=r.getClass().getField("y");
// f.setAccessible(true);
System.out.println(x.get(r));//field      ,       ,         
Field y=r.getClass().getDeclaredField("x");//       
y.setAccessible(true);//    
System.out.println(y.get(r));

Field[] fileds=r.getClass().getFields();//    
for (Field field : fileds) {
if(field.getType()==String.class){//      ==
String oldstr=(String)field.get(r);
String newstr=oldstr.replaceAll("a", "b");
field.set(r, newstr);//    
}

}
}

Method:메서드의 반사
public class ReflectPoint {
private  int x;
public int y;
public String str1="ball";
public String str2="basketball";
public String itcast="itcast";
public ReflectPoint(int x, int y) {
this.x = x;
this.y = y;
}

public static void staticMethodReflect(){
System.err.println("aaaaa");
}

public void methodReflect(String str){
System.err.println(str);
}

@Override
public String toString(){
return x+":"+y;

}
}
//  methodReflect  
Method method=r.getClass().getMethod("methodReflect",String.class);//           ,           class  
method.invoke(r,"aaaa");//                          
//       
Method method2=r.getClass().getMethod("staticMethodReflect",String.class);
method2.invoke(null,"bbbb");//       

배열의 반사는 다음과 같습니다.
Public static void main(string[] arg){
……..
}

Method method2=r.getClass().getMethod("main",String[].class);
method2.invoke(null,new object[]{new String[]{"abc","bcd"}});

//jdk는 이전 버전을 호환하기 위해 반사할 때 방법에 수조형삼이 있으면 호출할 때 컴파일러가 은밀하게 파라미터를 패키지로 만들 수 있기 때문에 호출할 때 다시 포장해야 한다
 

좋은 웹페이지 즐겨찾기