简体   繁体   English

将类作为参数传递给方法

[英]Passing class as argument to a method

I'm doing the following to establish the public methods of the class TestA. 我正在做以下事情来建立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. 我还需要为TestBTestC等做同样的事情,所以我想有一个函数,它接受一个类名并返回一个公共方法的String数组。 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. 如果我有一个Object参数,我必须在将它们发送给函数之前创建每个Class的实例。 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. 您还应该考虑使用Class.getMethods ,它只返回公共方法 - 但返回从超类继承的方法。

You can pass java.lang.Class instance it self , like shown below 你可以自己传递java.lang.Class实例,如下所示

 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());
      }
    }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM