흑마 프로그램--java 반사 실례
3189 단어 java 반사
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는 이전 버전을 호환하기 위해 반사할 때 방법에 수조형삼이 있으면 호출할 때 컴파일러가 은밀하게 파라미터를 패키지로 만들 수 있기 때문에 호출할 때 다시 포장해야 한다
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java 반사 및 동적 에이전트예를 들어 특정한 대상의 클래스 정의를 얻고, 클래스 성명의 속성과 방법을 얻고, 호출 방법이나 구조 대상을 사용하며, 심지어 실행할 때 클래스 정의를 수정할 수 있다. 2. 속성/방법을 얻을 때'Declared'가...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.