I'm doing the following to establish the public methods of the class TestA.
List<String> strings = new ArrayList<String>();
Method[] methods = TestA.class.getDeclaredMethods();
for(Method method : methods)
{
if(Modifier.isPublic(method.getModifiers()))
{
strings.add(method.getName());
}
}
I also need to do the same thing for TestB
, TestC
etc so I'd like to have a function which takes a class name and returns a String array of the public methods. How can I do this?
If I have an Object parameter, I will have to create an instance of each Class before I send them to the function. I wish to avoid this.
It sounds like you want:
public static List<String> getPublicDeclaredMethods(Class<?> clazz) {
List<String> strings = new ArrayList<String>();
Method[] methods = clazz.getDeclaredMethods();
for(Method method : methods) {
if(Modifier.isPublic(method.getModifiers())) {
strings.add(method.getName());
}
}
return strings;
}
Then call it with:
List<String> names = getPublicDeclaredMethods(TestA.class);
You should also consider using Class.getMethods
which only returns public methods anyway - but returns ones inherited from superclasses.
You can pass java.lang.Class
instance it self , like shown below
public void introspectClass(Class cls){
List<String> strings = new ArrayList<String>();
Method[] methods = cls.getDeclaredMethods();
for(Method method : methods)
{
if(Modifier.isPublic(method.getModifiers()))
{
strings.add(method.getName());
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.