Java爬坑--反射是这样搞的吗
1 import java.lang.reflect.Method; 2 3 /** 4 * Created by Q_先森 on 2017/12/12. 5 */ 6 public class MethodTest { 7 8 9 static void staticMethod() { 10 System.out.println("执行staticMethod()方法"); 11 } 12 13 public int publicMethod(int i) { 14 System.out.println("执行publicMethod()方法"); 15 return i * 20; 16 } 17 18 protected int protectedMethod(String s, int i) throws NumberFormatException { 19 System.out.println("执行protectedMethod()方法"); 20 return Integer.valueOf(s) + i; 21 } 22 23 private String privateMethod(String... strings) { 24 System.out.println("执行privateMethod()方法"); 25 StringBuffer stringBuffer = new StringBuffer(); 26 for (int i = 0; i < strings.length; i++) { 27 stringBuffer.append(strings[i]); 28 } 29 return stringBuffer.toString(); 30 } 31 32 public static void main(String[] args) { 33 //实例化一个对象: 34 MethodTest methodTest = new MethodTest(); 35 //获得所有的方法 36 Method[] declaredMethods = MethodTest.class.getDeclaredMethods(); 37 for (int i = 0; i < declaredMethods.length; i++) { 38 Method method = declaredMethods[i]; 39 System.out.println("名称:" + method.getName()); //方法名称 40 System.out.println("是否允许带有可变参数变量:" + method.isVarArgs()); 41 System.out.println("入口参数类型依次为:"); 42 //获得方法所有的参数类型 43 Class[] parameterTypes = method.getParameterTypes(); 44 for (int j = 0; j < parameterTypes.length; j++) { 45 System.out.println("parameterTypes[" + j + "]" + parameterTypes[j]); 46 } 47 48 System.out.println("返回值类型:" + method.getReturnType()); //获得方法返回值类型 49 System.out.println("可能抛出异常类型有:"); 50 Class[] exceptionTypes = method.getExceptionTypes(); //获得可能抛出的所有异常类型 51 for (int j = 0; j < exceptionTypes.length; j++) { 52 System.out.println("exceptionTypes[" + j + "]" + exceptionTypes[j]); 53 } 54 55 boolean isTurn = true; 56 while (isTurn) { 57 try { 58 isTurn = false; 59 if (i == 1) {// 这里i=0 是main方法 60 method.invoke(methodTest); 61 } else if (i == 2) { 62 System.out.println("返回值:" + method.invoke(methodTest, 5)); 63 } else if (i == 3) { 64 System.out.println("返回值:" + method.invoke(methodTest, "7", 5)); 65 } else if (i == 4) { 66 Object[] parameters = new Object[]{new String[]{"M", "W", "Q"}}; 67 System.out.println("返回值:" + method.invoke(methodTest, parameters)); 68 } 69 } catch (Exception e) { 70 System.out.println("在执行方法时抛出异常,执行setAccessible()方法"); 71 method.setAccessible(true); 72 isTurn = true; 73 } 74 } 75 System.out.println("============================割============================"); 76 } 77 } 78 }