本帖最后由 whs_nk 于 2013-4-8 13:55 编辑
今天有事,回来了准备自娱自乐以下搞个简单的反射,结果。。。。就是找不出哪里错了- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.HashSet;
- import java.util.Set;
- public class ReflectMethodTest {
- /**
- * @param args
- * @throws NoSuchMethodException
- * @throws InvocationTargetException
- * @throws IllegalAccessException
- * @throws IllegalArgumentException
- */
- public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
- // TODO Auto-generated method stub
- Set<Room> set = new HashSet<Room>();
- Room room1 = new Room("No.001",85);
- Room room2 = new Room("No.002",88);
- Room room3 = new Room("No.003",90);
-
- Method addMethod = set.getClass().getMethod("add", Room.class);
- addMethod.invoke(set, room1);
- addMethod.invoke(set, room2);
- addMethod.invoke(set, room3);
-
- //System.out.println(set.size());
- System.out.println(set.contains(room1));
- Method containsMethod = set.getClass().getMethod("contains", Room.class);
- System.out.println(containsMethod.invoke(set, room1));
- }
- }
- class Room{
- private String id;
- private int price;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public int getPrice() {
- return price;
- }
- public void setPrice(int price) {
- this.price = price;
- }
- public Room(String id, int price) {
- super();
- this.id = id;
- this.price = price;
- }
- }
复制代码 |