Java反射及使用实例
2018-03-30 11:55
381 查看
反射的概述
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。要想解剖一个类,必须先要获取到该类的字节码文件对象。而解剖使用的就是Class类中的方法.所以先要获取到每一个字节码文件对应的Class类型的对象.
ioc,aop都是基于Java的反射机制来是实现的。
如下具体实现一个实例:
/** * 通过对象,方法名称以及参数 来 调用方法 */ public static Object invokeMethod(Object owner, String methodName, Object... args) throws Exception { Class<?> clazz = owner.getClass(); Method method = findMethod(clazz, methodName); method.setAccessible(true); return method.invoke(owner, args); } /** * 通过对象,方法名称以及参数 来 调用方法 */ public static Object invokeMethod(Object owner, String methodName, Class<?>[] parameterTypes, Object... args) throws Exception { Class<?> clazz = owner.getClass(); Method method = findMethod(clazz, methodName, parameterTypes); method.setAccessible(true); return method.invoke(owner, args); }
其中的具体获取方法是:
/** * Attempt to find a {@link Method} on the supplied class with the supplied name * and parameter types. Searches all superclasses up to {@code Object}. * <p>Returns {@code null} if no {@link Method} can be found. * @param clazz the class to introspect * @param name the name of the method * @param paramTypes the parameter types of the method * (may be {@code null} to indicate any signature) * @return the Method object, or {@code null} if none found */ public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(name, "Method name must not be null"); Class<?> searchType = clazz; while (searchType != null) { Method[] methods = (searchType.isInterface() ? searchType.getMethods() : getDeclaredMethods(searchType)); for (Method method : methods) { if (name.equals(method.getName()) && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) { return method; } } searchType = searchType.getSuperclass(); } return null; }
相关文章推荐
- Java反射使用实例(http实体类转换)
- JAVA反射使用实例和class.getResource()得到URL中含有中文和空格乱码问题
- 使用反射创建Bean、Spring中是如何根据类名配置创建Bean实例、Java提供了Class类获取类别的字段和方法,包括构造方法
- Java反射API使用实例
- java反射和自定义注解的使用实例
- Java使用new和反射实例化内部类对象
- 使用java反射中的getMethod,invoke方法调用对象方法的实例
- Java反射学习总结四(动态代理使用实例和内部原理解析)
- java使用反射实例
- 使用java反射根据参数返回类的实例
- java 程序加载过程---3--类中申明同时申明类的静态对象 创建类的实例 访问类的静态变量 调用类的静态方法 使用反射方法 初始化类的子类对象 直接使用java.exe 调用某个类
- Java反射学习总结四(动态代理使用实例和内部原理解析)
- java学习---使用反射创建类的实例
- java反射使用实例
- 使用反射创建Bean、Spring中是如何根据类名配置创建Bean实例、Java提供了Class类获取类别的字段和方法,包括构造方法
- 使用技巧:Java实现随机验证码功能实例
- 使用java解析xml的实例程序
- Java反射经典实例 Java Reflection Cookbook
- java.io.file使用实例
- 使用Java5特性来简化反射编程