如何通过反射找出方法的可见性? [英] How can I find out what a method's visibility is via reflection?

查看:145
本文介绍了如何通过反射找出方法的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:



我正在尝试学习/练习TDD,并决定需要创建一个不变的类。



为了测试不变性不变(您能说吗?),我想我只是通过反射来调用类中的所有公共方法,然后检查之后类是否没有更改。这样一来,以后我就不太可能不小心打破不变式。 b

策略:




  • 使用 getMethods()



使用 getMethods(),我仅获得公共接口,但是当然这也包括所有继承的方法。
然后的问题是,诸如wait()和notify()之类的方法会导致InvocationTargetExceptions,因为我还没有进行同步等。




  • 使用 getDeclaredMethods()



(天真的吗?)只有我声明的方法才能够打破类的不变性,我尝试使用 getDeclaredMethods()代替。
不幸的是,这将调用在类中声明的所有方法(私有和公共方法),而不是超类。私有方法显然不相关,因为它们允许打破不变性。



问题:



所以我的问题是是,如何确定通过 getDeclaredMethods()获得的方法是否公开,以便可以通过反射调用它?没有任何东西让我浏览文档...



我可以看到其他解决此问题的方法,例如专门忽略了诸如wait()等方法,但这似乎更加骇客

解决方案

作为,找到要解决的问题,并可以使用 Method.getModifiers() 确定与该方法关联的修饰符。



例如

  if(Modifier.isPublic(someMethod.getModifiers()){
//等。
}


Context:

I'm trying to learn/practice TDD and decided I needed to create an immutable class.

To test the 'immutability invariant' (can you say that?) I thought I would just call all the public methods in the class via reflection and then check that the class had not changed afterwards. That way I would be unlikely to break the invariant carelessly later on. This may or may not be practical/valid in itself but I thought it would also be an exercise in reflection for me.

Strategies:

  • Use getMethods():

Using getMethods(), I get the public interface only, but of course this includes all the inherited methods as well. The problem then is that methods such as wait() and notify() cause InvocationTargetExceptions because I haven't synchronized etc...

  • Use getDeclaredMethods():

(Naively?) assuming that only the methods that I declare are able to break the class's immutability, I tried using getDeclaredMethods() instead. Unfortunately this calls all methods, private and public that are declared in the class, but not super classes. The private methods obviously are not relevant as they are allowed to break immutability.

Question:

So my question is, how can I find out whether a method obtained via getDeclaredMethods() is public or not so that I can invoke it via reflection? Nothing jumped out at me looking through the docs...

I can see other ways of solving this problem like specifically ignoring methods like wait() etc but that seems even hackier than I can handle.

解决方案

As mentioned in the comments, you can use Method.getModifiers() to determine the modifiers associated with the method.

E.g.

if (Modifier.isPublic(someMethod.getModifiers()) {
  // etc.
}

这篇关于如何通过反射找出方法的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆