转载请注明:http://blog.csdn.net/uniquewonderq
1.如何获取某个方法
方法的名称和方法的参数列表才能唯一决定某个方法
2.方法的反射操作
method.invoke(对象,参数列表)
1.获取一个方法就是获取类的信息,获取类的信息,首先要获取类的类类型。
2.获取方法名称和参数列表来决定
getMethod获取的是public的方法
getDeclaredMethod获取所有声明的方法
<span style="font-size:18px;">package com.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author wonderq
*/
public class MethodReflect {
public static void main(String[] args) {
//获取print方法,但是有两个,这里获取print(int ,int)
//1.获取一个方法就是获取类的信息,获取类的信息,首先要获取类的类类型。
A a1=new A();
Class c=a1.getClass();
try {
/*
2.获取方法名称和参数列表来决定
getMethod获取的是public的方法
getDeclaredMethod获取所有声明的方法
*/
Method m=c.getMethod("print", int.class,int.class);//第二个参数是变参
//方法的反射操作;
// a1.print(10, 20);方法的反射操作是用m对象来进行方法调用和a1.print调用的效果是一样的
//方法如果没有返回值,返回null,有返回值返回具体的返回值
//Object o=m.invoke(a1, new Object[]{10,20});
Object o=m.invoke(a1, 10,20);
System.out.println("=========================");
//获取方法print(string,string)的对象
Method m1=c.getMethod("print", String.class,String.class);
//对方法进行反射操作。
//a1.print("hello","world");
o=m1.invoke(a1, "hello","WORld");//与上述效果一致
System.out.println("=========================");
Method m2=c.getMethod("print");//这个时候第二个参数,没有,那么就不传,变参可以为空
m2.invoke(a1);
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
} catch (SecurityException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
Logger.getLogger(MethodReflect.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(MethodReflect.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(MethodReflect.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class A{
public void print(){
System.out.println("helloworld!");
}
public void print(int a,int b){
System.out.println("a+b="+(a+b));
}
public void print(String a,String b){
System.out.println(a.toUpperCase()+","+b.toLowerCase());
}
}</span>
输出结果:
run:
a+b=30
=========================
HELLO,world
=========================
helloworld!
这就是获取方法对象,然后用方法对象进行反射操作。
Java--Reflect(反射)专题5——方法反射的基本操作
原文地址:http://blog.csdn.net/uniquewonderq/article/details/46591635