JAVA 반사 연습
1883 단어 JAVA 베이스.
제목
요구 사항:ArrayList의 대상입니다. 이 집합에 문자열 데이터를 추가하면 어떻게 실현합니까?
알림: 범용은 컴파일링 기간에만 유효하며, 실행 기간에는 지워집니다
public static void main(String[] args) throws Exception {
ArrayList list = new ArrayList<>();
list.add(111);
list.add(222);
Class clazz = Class.forName("java.util.ArrayList"); //
Method m = clazz.getMethod("add", Object.class); // add
m.invoke(list, "abc");
System.out.println(list);
}
2. 제목 2:
요구 사항: 알려진 클래스는 다음과 같습니다.
public class DemoClass {
public void run() {
System.out.println("welcome to heima!");
}
}
(1) 클래스의 전체 이름인 Properties 형식의 프로필을 작성합니다.(2) 이 Properties 프로필을 읽고 클래스의 전체 이름을 얻으며 클래스를 불러오고 반사적으로run 방법을 실행합니다.
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("xxx.properties"));// xxx.properties
Class clazz = Class.forName(br.readLine()); // ,
DemoClass dc = (DemoClass) clazz.newInstance(); //
dc.run();
}
제목
요구: obj 대상의propertyName이라는 속성의 값을value로 설정할 수 있는 일반적인 방법
public class Tool {
public void setProperty(Object obj, String propertyName, Object value) throws Exception {
Class clazz = obj.getClass(); //
Field f = clazz.getDeclaredField(propertyName); //
f.setAccessible(true); //
f.set(obj, value);
}
}
public static void main(String[] args) throws Exception {
Student s = new Student(" ", 23);
System.out.println(s);
Tool t = new Tool();
t.setProperty(s, "name", " ");
System.out.println(s);
}