[英]Generic method that accepts two types of List
I want to write a function that can accept two similar types. 我想编写一个可以接受两种相似类型的函数。 But not same.
但是不一样。
MyClassA {
abc()
a2b()
}
MyClassB {
abc()
a3b()
}
One method is same in these two. 这两种方法中的一种是相同的。 The function should accept list of any of these two types and I want to invoke abc() on objects in the list.
该函数应接受这两种类型中任何一种的列表,并且我想在列表中的对象上调用abc()。
This does not seem to help: 这似乎没有帮助:
private <T> Set<MyclassX> createObject(List<T> classes) {
Set<MyclassX> x;
if ( T instanceof MyClassA) {
for ( MyClassA a : classes ) {
if (a.abc().equals("somethig")) {
x.add( t.abc());
}
}
}
return x;
}
I don't even need to check instanceof
. 我什至不需要检查
instanceof
。 I just need to iterate through the list and compare the values. 我只需要遍历列表并比较值即可。 if there is a match, then call the method
abc()
如果有匹配项,则调用方法
abc()
Just create a common interface and make MyClassA and MyClassB implement it: 只需创建一个通用接口并使MyClassA和MyClassB实现它:
interface MyClass {
void abc();
}
I suggest you to use abstract super class
like this: 我建议您使用这样的
abstract super class
:
abstract SuperClass{
abc();
abstract ab(); // Only if the other methods share signatures
}
MyClassA extends SuperClass {
ab();
}
MyClassB extends SuperClass{
ab();
}
private <T> Set<? extends SuperClass> createObject(List<T> classes) {
...
}
If you only want to iterate over a collection that contains instances of MyClassA
and MyClassB
, then call the method abc()
on those instances. 如果只想遍历包含
MyClassA
和MyClassB
实例的集合,则在这些实例上调用方法abc()
。 This can be work well with JPA
because there is an annotation so called MappedSuperclass . 这可以与
JPA
一起很好地使用,因为有一个称为MappedSuperclass的注释。
This way you can decompose the same logic from descendant classes in a way that fits with your requirements and can be used with generics. 这样,您就可以以符合您的需求并可以与泛型一起使用的方式,从子孙类中分解相同的逻辑。 Here is a Hibernate example of how to use
这是一个如何使用的Hibernate示例
Using generics, you can do this: 使用泛型,您可以执行以下操作:
private <T> Set<MyclassX> createObject(List<T> classes) {
Set<MyclassX> x;
for ( T a : classes ) {
if (a.abc().equals("somethig")) {
x.add( t.abc());
}
}
}
return x;
}
Assuming that t.abc()
returns a MyclassX
. 假设
t.abc()
返回MyclassX
。 (And I mean this literally, I'm not assuming that the X
stands for something else.) (我的意思是从字面上看,我并不是假设
X
代表其他含义。)
Type information can be passed in as an argument 类型信息可以作为参数传递
<T> void method(Class<T> clazz, List<T> list)
{
if(clazz==MyClassA.class)
{
@SuppressWarnings("unchecked)
List<MyClassA> listA = (List<MyClassA>)list;
....
}
else if...
A better solution is probably to convert a List<MyClassX>
to a List<Abc>
before passing it in 更好的解决方案可能是在将
List<MyClassX>
转换为List<Abc>
之前将其转换为
interface ABC
abc()
void method(List<Abc> list)
the conversion is probably going to be easy in java8 在java8中转换可能会很容易
List<MyClassA> list1 = ...
method( list1.map( e->e.abc() ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.