[英]Can acceptable type be restricted for a generic method in java?
I have a similar requirement to this question .我对这个问题有类似的要求。 I would like to generify a method but restrict the types the acceptable by the generic parameter.
我想泛化一个方法,但限制泛型参数可接受的类型。 Currently what I do is attempt to cast to the acceptable types in the method but seems cumbersome if dealing with more than 2 or 3 types.
目前我所做的是尝试在方法中强制转换为可接受的类型,但如果处理超过 2 或 3 种类型,则似乎很麻烦。
EDIT :编辑:
The types may not be of the same base class.类型可能不是相同的基类。 Apologies for not mentioning this earlier.
很抱歉之前没有提到这一点。
For this, You must have a base class so that you can do this.为此,您必须有一个基类才能执行此操作。
public class Person {
String name;
List<Profession> professions;
int age;
}
public class Doctor {
String university;
Boolean doctorate;
public void work() {
// do work
}
}
public class Teacher {
List<Grade> grades;
float salary;
public void work() {
// do work
}
}
public class Animal<T> {
T type;
}
So, now if you want to write a method which is generic and applies to all, You can do something like this,所以,现在如果你想写一个通用的并且适用于所有人的方法,你可以做这样的事情,
public void doSomething(Animal<T extends Person> human) {
human.work();
}
If the class is not of type Person
, it will show a compilation error.如果该类不是
Person
类型,则会显示编译错误。
UPD1: UPD1:
In the case, all the classes do not have a common base class.在这种情况下,所有的类都没有一个共同的基类。 There is some functionality that makes them unique.
有一些功能使它们独一无二。 By this, we can consider them to have a common function, which we can and should add using an interface .
通过这种方式,我们可以将它们视为具有通用功能,我们可以并且应该使用interface添加该功能。
Let's look at some code,让我们看一些代码,
public class Human implements Growable {
public void grow() {
// human grow code
}
}
public class Plant implements Growable {
public void grow() {
// plant grow code
}
}
public class Table {
// does not grows
}
public class GrowService {
public static void grow(Growable growable) {
growable.grow();
}
}
interface Growable {
public void grow();
}
And by calling the below method, we can achieve this通过调用下面的方法,我们可以实现这个
// Works fine
GrowingService.grow(new Plant());
// throws compilation error
GrowingService.grow(new Table());
Java Generics allow basic wildcards such as <T>
but also more specifics like Java 泛型允许使用基本的通配符,例如
<T>
但也允许使用更具体的通配符,例如
<T extends Number>
which means any type T that is Number or a subclass of it or <T extends Number>
表示任何类型 T 是 Number 或其子类或
<T super Number>
which means T can be Number or any superclass of Number all the way up to Object. <T super Number>
表示 T 可以是 Number 或任何 Number 的超类,一直到 Object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.