简体   繁体   English

java,泛型 - 如何使用类型T对类进行参数化,其中BOTH:扩展并实现某些类型

[英]java, generics - how to parametrize a class with a type T which BOTH: extends and implements sth

I want to type class members, as well as args for methods, in a type T, which has to be a Node and implement my own interface Linkable. 我想在类型T中键入类成员以及方法的args,它必须是一个Node并实现我自己的接口Linkable。

Essentially, I would like to limit the vars to the small section of the inheritance 'tree' between Node and Linkable. 本质上,我想将变量限制在Node和Linkable之间的继承“树”的小部分。 Reason being I don't want to have to do all the casting inside the class, depending if I need to call methods of Node or methods of Linkable. 原因是我不想在类中进行所有的转换,这取决于我是否需要调用Node的方法或Linkable的方法。

At the moment in my project I know I'm using only Nodes which implement Linkable, but this condition is not enforced in any way. 在我的项目中,我知道我只使用实现Linkable的节点,但这种情况不会以任何方式强制执行。

Pseudo-code below (only for illustration): 下面的伪代码(仅用于说明):

public class MyClass <T extends ??> {

T node1;
Bounds bounds1;

bounds1 = node1.boundsInParentProperty(); //Node specific method

node1.linkableSpecificMethod(); //method defined in Linkable interface
//....
}

There are two things that help you: 有两件事可以帮助你:

  • Generics do not distinguish between Interfaces and Classes. 泛型不区分接口和类。
  • Generics support ampersand for listing multiple types. 泛型支持用于列出多种类型的&符号。

That said, what you probably want is this: 那就是说,你可能想要的是:

class YourClass<T extends Node & Linkable> {
}

暂无
暂无

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

相关问题 泛型类型 T BUT 的类实例,它使用泛型扩展超类 - Class instance of generics type T BUT which extends a super class with generics Java Generics - 实现和扩展 - Java Generics - implements and extends Java:如何创建一个泛型类,它需要一个扩展类并实现接口的数据类型? - Java: how to create a generic class that requires a data type which extends a class and implements an interface? Java Generics创建扩展A类并实现接口B的对象列表 - Java Generics create list of objects which extends class A and implements interface B 实现vs在Java中的泛型中扩展 - implements vs extends in generics in Java 为什么允许“extends T”而不是“implements T”? - Why is "extends T" allowed but not "implements T"? 如何区分kotlin的类继承(在java中扩展)和接口实现(实现)这里kotlin使用(:)两者? - How to Differentiate between kotlin's class inheritence(extends in java) and interface implementation(implements in ) here kotlin uses ( : ) for both? 了解Java泛型 <T extends Class> 和 <? extends Class> - Understanding Java Generics <T extends Class> and <? extends Class> 如何创建具有扩展另一个类并实现接口的类型参数的基适配器? - How to create base adapter which has type parameter that extends another class and implements an interface? 是否等于Java类中的实现,该类实现了扩展Iterable的接口? - Equals implementation in a java-class which implements an interface that extends Iterable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM