本文以我以前的文章为基础 。 在本文中,我们将看到如何使用Java Reflection检索类相关信息。 我们将重点介绍方法名称。
注意:我将创建一个单独的反射器实用程序类,在该类中,我们在其构造函数中输入一个目标类,然后使用一个单独的方法检索信息。 这样,我们可以隔离我们的需求。 在开始之前,请先查看此内容 。
如何在一个类中获取所有声明的方法名称?
这意味着,我们将获得在类内部声明的方法名称(公共,私有,默认,受保护),即不是继承的方法。
public String[] getAllOwnMethodNames(){ArrayList<String> allMethods = new ArrayList<String>();for(Method aMethod : myClass.getDeclaredMethods()){ allMethods.add("Method Name : "+aMethod.getName()+" , Full Name : "+aMethod.toString());}return allMethods.toArray(new String[allMethods.size()]);}
如何从一个类(包括其自己的超类,接口的继承的,实现的方法)中访问所有方法名称?
public String[] getAllPubliAndInheritedMethodNames(){ArrayList<String> allMethods = new ArrayList<String>();for(Method aMethod : myClass.getMethods()){ allMethods.add("Method Name : "+aMethod.getName()+" , Full Name : "+aMethod.toString());}return allMethods.toArray(new String[allMethods.size()]);}
注意:要获得详细信息,我们使用getName()和toString()方法。
对于这两种情况,我们都可以指定方法名称来获取该特定方法。
myClass.getDeclaredMethod(<Name of the method as string>, parameter of that method)
myClass.getMethod(<Name of the method as string>, parameter of that method)
在这两种情况下,我们都需要知道方法的名称。 有时,对于一个类,我们需要知道某个方法是Getter还是setter方法。 我们可以应用一个小的字符串过滤器,如下所示:
要知道它是否是Getter方法:
aMethod.getName().startsWith("set");
要知道它是否是一个Setter方法:
aMethod.getName().startsWith("get");
翻译自: https://www.javacodegeeks.com/2015/01/how-to-get-all-method-information-under-a-class-in-java-reflection.html