您的位置:首页 > 编程语言 > Java开发

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反射 Java invoke