简体   繁体   English

方法参数必须是实现某个接口的某个类的obj

[英]Method parameter must be obj of certain class that implements certain interface

How to declare a method with parameter which must be same time a certain class which implements certain interface without declaring a special class for this? 如何声明一个带参数的方法,该方法必须同时实现某个接口,而不为此声明一个特殊的类?
Assume i have declared class ImageX and also declared interface Tagging. 假设我已经声明了类ImageX并且还声明了接口Tagging。 So I need to create some other class or method which has to receive only instances of ImageX which implements Tagging interface. 所以我需要创建一些其他类或方法,它们只需要接收实现Tagging接口的ImageX实例。 How to declare such method? 如何申报这种方法? something like 就像是

private void someMethod (ImageX<Tagging> obj){} 

but this is not correct of course. 但这当然不正确。 Yes I could check the obj if it implements needed interface but I want that check in parameters. 是的我可以检查obj是否实现了所需的接口,但我想要检查参数。 And what if it is not some method but a constructor... 如果它不是某种方法而是构造函数会怎么样?
am I asking about generics maybe? 我可能会询问仿制药吗?

您可以使方法通用,并且只使用类型交集接受同时属于ImageX和标记的对象:

private <T extends ImageX & Tagging> void someMethod (T obj){} 

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

相关问题 想知道某个类是否实现了特定的接口 - Want to know if a certain class implements an specific interface 确定类的超类是否在Java中实现特定接口 - determine whether a class's superclass implements a certain interface in java 实现特定接口的Java属性 - Java attribute which implements a certain Interface 修复类,以确保仅在实现特定接口时将其添加到其列表中-Java - Fixing a class to ensure that it adds objects to its list, only if it implements a certain interface - Java 如何说服Java构造函数接受包含其类实现特定接口的对象的列表 - How to convince a Java Constructor to accept a List containing objects whose Class implements a certain Interface 如何指定实现接口的引用方法参数 - How To Specify a Reference Method Parameter that Implements an Interface 通用方法参数:实现接口的枚举 - Generic method parameter: enum which implements an interface 当类实现接口时,为什么ServletConfig obj传递给GenericServlet的init()? - Why is ServletConfig obj passed to init() of GenericServlet when the class implements the interface? 从实现接口的类中调用方法(java) - calling a method from a class that implements an interface (java) 哪个类在运行时实现接口的方法 - Which class implements interface's method at runtime
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM