反射的使用方法
userSeriver接口
public interface UserService {
void add();
int delete(String id);
int update(String id, String name, String age);
int insert(String id, String name, String age);
}
UserServiceImpl 实现类
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("add个啥,你啥也没传");
}
@Override
public int delete(String id) {
System.out.println("id:"+id+"被删除了");
return 0;
}
@Override
public int update(String id, String name, String age) {
System.out.println("id:"+id+"修改成功[name:"+name+"age:"+age+"]");
return 1;
}
@Override
public int insert(String id, String name, String age) {
System.out.println("插入成功[id:"+id+"name:"+name+"age:"+age+"]");
return 2;
}
}
MainTest测试类
public class MainTest {
public static void main(String[] args) {
try {
Class<?> clazz1 = Class.forName("com.test.UserServiceImpl");
Method method1 = clazz1.getMethod("update", String.class, String.class, String.class);
Object invoke1 = method1.invoke(clazz1.newInstance(), "id100","王大拿","51");
System.out.println(invoke1);
Class<?> clazz2 = UserServiceImpl.class;
for (Method method : clazz2.getMethods()) {
if (method.getName().equals("insert")) {
Method thisMethod = clazz2.getMethod(method.getName(), method.getParameterTypes());
Object obj = thisMethod.invoke(clazz2.newInstance(), "1", "张大炮", "28");
System.out.println(obj);
}
}
UserService user = new UserServiceImpl();
Class<?> clazz3 = user.getClass();
Method method3 = clazz3.getMethod("add");
Object invoke3 = method3.invoke(clazz3.newInstance());
System.out.println(invoke3);
} catch (Exception e) {
e.printStackTrace(http://www.my516.com);
}
}
}
---------------------