前言
最近打算手写一个RPC,但奈何自己Java基础知识中的反射就很欠缺,第一章就看不太懂了,特地编写了几个小Demo验证一下Java中关于反射的基础知识。
目录组织结构
代码编写
// TestService接口
package reflect.testServices;
import main.version1.v1.common.pojo.User;
public interface TestService {
User getUserById(Integer id);
Integer insertUserById(User user);
}
// TestService1接口
package reflect.testServices;
import main.version1.v1.common.pojo.User;
public interface TestService1 {
User getUserByName(String name);
}
// TestServiceImpl实现类
package reflect.testServices.impl;
import main.version1.v1.common.pojo.User;
import reflect.testServices.TestService;
import reflect.testServices.TestService1;
public class TestServiceImpl implements TestService, TestService1 {
@Override
public User getUserById(Integer id) {
return null;
}
@Override
public Integer insertUserById(User user) {
return null;
}
@Override
public User getUserByName(String name) {
return null;
}
}
// 测试Demo编写
package reflect;
import reflect.testServices.TestService;
import reflect.testServices.impl.TestServiceImpl;
import java.lang.reflect.Method;
public class Demo01 {
public static void main(String[] args) throws NoSuchMethodException {
System.out.println("=====");
// 获取方法名
Method getUserById = TestService.class.getMethod("getUserById", Integer.class);
System.out.println(getUserById);
// 获取方法对应的接口名
System.out.println(getUserById.getDeclaringClass().getName());
System.out.println("======");
TestService testService = new TestServiceImpl();
// 获取实现的接口字节码集合
Class<?>[] interfaces = testService.getClass().getInterfaces();
String name = testService.getClass().getName();
System.out.println(name);
// 遍历接口字节码集合
for (Class<?> interfacea : interfaces) {
// 获取接口名称
System.out.println(interfacea.getName());
// 遍历各个接口中定义的所有方法
Method[] declaredMethods = interfacea.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println("innnnnnnn" + declaredMethod);
}
}
System.out.println("=========");
// 获取实现类中定义的所有方法
Method[] methods = testService.getClass().getDeclaredMethods();
for (Method method : methods) {
System.out.println(method);
}
}
}