简体   繁体   English

返回通用类类型

[英]Return generic class type

I have a method that might return Class A or Class B. How can I define its return type to be generic, independent of what class type is returned. 我有一个可能返回Class A或Class B的方法。如何将其返回类型定义为泛型,而与返回的类类型无关。 For eg 例如

public <Generic_Class_Return_Type> showForm() {
   if (true)
      return new ClassA();
   else 
      return new ClassB();
}

Not really sure if you need generics in this case, however you can parameterize either the whole class or just the method and then use reflection like this: 不太确定在这种情况下是否需要泛型,但是可以对整个类或仅对方法进行参数化,然后像这样使用反射:

public <T> T getForm() {
  Class<T> clazz = (Class<T>) ((true) ? Foo.class : Bar.class);
  Constructor<T> ctor = clazz.getConstructor();
  return ctor.newInstance();
}

However if you specify your use case, we can further suggest if going generics is the way, or if you'd better use standard polymorphism. 但是,如果您指定用例,我们可以进一步建议使用通用方法还是最好使用标准多态性。

You could use an interface both classes implement like this: 您可以使用两个类都实现的接口,如下所示:

public SomeInterface showForm() {
   if (true)
      return new ClassA();
   else 
      return new ClassB();
}

class ClassA implements SomeInterface{}
class ClassB implements SomeInterface{}
public object showForm()
{
   if (true)
      return new ClassA();
   else
      return new ClassB(); 
}

or 要么

public superClassName showForm()
{
   if (true)
      return new ClassA();
   else
      return new ClassB();
}

The simplest way is to return them as an Object. 最简单的方法是将它们作为对象返回。

public Object showForm() {
   if (true)
      return new ClassA();
   else 
      return new ClassB();
}

It's not so useful though, a far more useful solution would be to have them either extend a common class or implement a common interface. 不过,它不是那么有用,一种更有用的解决方案是让它们扩展公共类或实现公共接口。

public CommonInterface showForm() {
   if (true)
      return new ClassA();
   else 
      return new ClassB();
}

class ClassA implements CommonInterface { }
class ClassB implements CommonInterface { }
interface CommonInterface { }

Or 要么

public CommonClass showForm() {
   if (true)
      return new ClassA();
   else 
      return new ClassB();
}

class ClassA extends CommonClass { }
class ClassB extends CommonClass { }
class CommonClass { }

Generics 泛型

If you want to use generics then ClassA and ClassB would need to be the same Class, modified by some generic type eg. 如果要使用泛型,则ClassAClassB必须是同一类,并通过某些泛型类型进行了修改。 Class<T> . Class<T> Whether generics are relevant all depends on the implementation of your classes. 泛型是否相关都取决于类的实现。 You're probably best to go with an interface or base class. 您最好是使用接口或基类。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM