getMethod是Class类的,下面是个小程序,当方法私有会输出时会有异常,希望能解决你的问题:
import java.lang.reflect.Method;
import java.util.Date;
public class Program
{
public static void main(String[] args)
{
// 取得本类对象对应的类名
Program program = new Program();
Class progClass = program.getClass();
try
{
// 取得sayHello方法
Method helloMethod = progClass.getMethod(
"sayHello", null);
System.out.println("Public method found: " +
helloMethod.toString());
}
catch (NoSuchMethodException ex)
{
System.out.println("Method either doesn't exist " +
"or is not public: " + ex.toString());
}
try
{
// 取得setStr方法
Class[] args1 = new Class[1];
args1[0] = String.class;
Method strMethod = progClass.getMethod(
"setStr", args1);
System.out.println("Public method found: " +
strMethod.toString());
}
catch (NoSuchMethodException ex)
{
System.out.println("Method either doesn't exist " +
"or is not public: " + ex.toString());
}
try
{
//取得setDate方法
Class[] args2 = new Class[1];
args2[0] = Date.class;
Method dateMethod = progClass.getMethod(
"setDate", args2);
System.out.println("Public method found: " +
dateMethod.toString());
}
catch (NoSuchMethodException ex)
{
System.out.println("Method either doesn't exist " +
"or is not public: " + ex.toString());
}
try
{
// 取得 setI方法.
Class[] args3 = new Class[1];
args3[0] = Integer.TYPE;
Method iMethod = progClass.getMethod(
"setI", args3);
System.out.println("Public method found: " +
iMethod.toString());
}
catch (NoSuchMethodException ex)
{
System.out.println("Method either doesn't exist " +
"or is not public: " + ex.toString());
}
}
public String sayHello()
{
return "Hello!";
}
public void setStr(String str)
{
this.str = str;
}
private void setDate(Date date)
{
this.date = date;
}
private void setI(int i)
{
this.i = i;
}
public String str = "Hello";
private Date date = new Date();
protected int i = 0;
}
|