前言
最近打算手写一个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 {@Overridepublic User getUserById(Integer id) {return null;}@Overridepublic Integer insertUserById(User user) {return null;}@Overridepublic 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);}}
}