java使用反射列出类的所有方法,java反射列出类,在下面的例子中我们通过j
分享于 点击 18284 次 点评:16
java使用反射列出类的所有方法,java反射列出类,在下面的例子中我们通过j
在下面的例子中我们通过java的反射机制获得内置类Person的所有方法的定义。
首先我们通过Person.class得到类的Class实例。获得Class实例之后我们就可以通过getDeclaredMethods()
方法获得类的所有方法的定义。
可以通过Method实例的getName()方法获得方法名称。
import java.lang.reflect.Method;/** * * @author byrx.net */public class Main { /** * Lists the methods of a class using the Reflection api. */ public void listMethodsUsingReflection() { //Obtain the Class instance Class personClass = Person.class; //Get the methods Method[] methods = personClass.getDeclaredMethods(); //Loop through the methods and print out their names for (Method method : methods) { System.out.println(method.getName()); } } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().listMethodsUsingReflection(); } class Person { private String firstname; private String lastname; private String age; public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }}
上面代码输出:
getFirstnamesetFirstnamegetLastnamesetLastnamegetAgesetAge
用户点评