反照机制(2)
反射机制(2)
package com.bjsxt.demo; import java.lang.reflect.Method; class Tools { public void print() { System.out.println("Tools类中无参无返回值的方法。"); } public String getInfo() { //无参有返回值 return "Hello MLDN."; } public int add(int x, int y) { return x+y; } } public class APIDemo { /** * @param args */ public static void main(String[] args) throws Exception { Class<?> cls = Class.forName("com.bjsxt.demo.Tools"); Method met[] = cls.getMethods(); for(int x = 0; x < met.length; x++) { System.out.println(met[x]); } } } 首先为了说明出Method方法的功能,先取得Tools类中的全部方法,当然,这些方法应该包含了继承而来的
package com.bjsxt.demo; import java.lang.reflect.Method; import java.lang.reflect.Modifier; class Tools { public void print() { System.out.println("Tools类中无参无返回值的方法。"); } public String getInfo() { //无参有返回值 return "Hello MLDN."; } public int add(int x, int y) { return x+y; } } public class APIDemo { /** * @param args */ public static void main(String[] args) throws Exception { Class<?> cls = Class.forName("com.bjsxt.demo.Tools"); Method met[] = cls.getMethods(); for(int x = 0; x < met.length; x++) { System.out.print(Modifier.toString(met[x].getModifiers()) + " "); Class<?> returnType = met[x].getReturnType(); System.out.print(returnType.getName() + " "); System.out.print(met[x].getName()); System.out.print("("); Class<?>[] param = met[x].getParameterTypes(); for(int i = 0; i < param.length; i++) { System.out.print(param[i].getName() + " arg-" + i); if(i != param.length - 1) { System.out.print(","); } } System.out.print(")"); Class<?> exp[] = met[x].getExceptionTypes(); if(exp.length > 0) { System.out.print(" throws "); for(int y = 0; y < exp.length; y++) { System.out.print(exp[y].getName()); if(y != exp.length - 1) { System.out.print(","); } } } System.out.println(); } } } 首先为了说明出Method方法的功能,先取得Tools类中的全部方法