通过反射机制获取某个特定的方法
-
反射是通过 方法名+形参列表来区分各个方法的(形参列表要用class类型。加.class)
-
示例代码
import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class ReflectTest10 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { //创建class对象 Class c=Class.forName("com.shige.Reflect.CustomerService"); //获取某个特定得方法 Method method=c.getDeclaredMethod("login", String.class, String.class); // 方法名 + 形参列表来区分 //获取形参Class数组 Class[] parameters=method.getParameterTypes(); //输出方法头部 System.out.print(Modifier.toString(method.getModifiers()) +" "+method.getReturnType().getSimpleName()+" " +method.getName()+"("); //形参输出 for (int i = 0; i <parameters.length ; i++) { if(i!=parameters.length-1){ System.out.print(parameters[i].getSimpleName()+","); }else{ System.out.print(parameters[i].getSimpleName()+"){}"); } } } }