我的情况类似于以下示例。
我有两个不同的对象,并且已经从它们创建了实例。我需要将这些实例作为常规参数传递给方法参数。
我尝试将方法参数作为Class obj传递,但没有成功
Class A
{
A()
{
List<String>collection = new ArrayList<>();
}
}
Class B
{
B()
{
List<String>collection = new ArrayList<>();
}
}
Class Main()
{
A a = new A();
B b = new B();
methodTest(a);
methodTest(b);
void methodTest(Class<T> genericObj)
{
genericObj.collection.add("1");
// I need to pass both the instance A and instance B to
genericObj
}
}
需要一些建议。
答案 0 :(得分:0)
您不会将泛型传递给方法,因为泛型是一种类型,而不是对象。
您要做的是,您传递一个对象;在类中声明了泛型。
例如
public class Test <T extends ClasThatHasCollection> {
void methodTest(T genericObj) {
genericObj.collection.add("1");
}
}
但是,就您而言,仿制药似乎是一种过大的杀伤力!
只有一个具有.collection实例变量的父类P;并让A类和B类都扩展P;并将对象类型P传递给methodTest:
public class P {
public Collection collection;
// ....
}
public class A extends P {
}
void methodTest(P genericObj) {
P.collection.add("1");
}
答案 1 :(得分:-1)
最简单的方法是创建一个基类,并让A和B继承自它。
在方法中,将基类用作类型。
这是有效的,因为A和B都对其进行了扩展。
例如:
class Base {
List<String> collection;
Base() {
collection = new ArrayList<>();
}
}
class A extends Base{
A(){
super()
}
}
class B extend Base{
B(){
super()
}
}
void methodTest(Base genericObj)
{
genericObj.collection.add("1");
}
另一种可能性是使用界面。如果集合的类型不同,因此未在基础对象中定义,这将很有用。
使用界面:
interface MyInterface{
public ArrayList<> getCollection();
}
class A implements MyInterface {
List<String> collection;
A(){
collection = new ArrayList<>();
}
public ArrayList<> getCollection(){
return collection;
}
}
class B implements MyInterface{
List<String> collection;
B(){
collection = new ArrayList<>();
}
public ArrayList<> getCollection(){
return collection;
}
}
void methodTest(MyInterface genericObj)
{
genericObj.getCollection().add("1");
}