[英]Is there a way to check in Java runtime if an object has a specific method?
I have a class and it has multiple subclasses which each implement their own methods. 我有一个类,它有多个子类,每个子类都实现自己的方法。 Some of these subclasses have common method which I need to call.
其中一些子类有我需要调用的常用方法。 Is there a way in java to know if the object has a method (without using
instanceof
)? 有没有办法在java中知道对象是否有方法(不使用
instanceof
)?
This probably points to a design flaw, but you could always use reflection to check if a method exists: 这可能指向设计缺陷,但您可以始终使用反射来检查方法是否存在:
public static boolean hasMethod(Object obj, String methodName) {
return Arrays.stream(obj.getClass().getMethods())
.anyMatch(m -> m.getName().equals(methodName));
}
This, of course, could be refined to include the method's signature too, but the basic idea remains the same. 当然,这可以改进以包括方法的签名,但基本思想保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.