如何返回接口实现的类型

时间:2018-03-27 11:44:51

标签: java

想法是使导出类中的ExporParts函数适用于任何WebData衍生物。为此,我需要知道T类类及其名称。

建议的解决方案有效,但我必须手动编写。我想知道是否可能只知道有关类型的当前信息的类名。

另一方面,反思不是一种选择。太贵了。

感谢。

实施例

// Data gathered at runtime, may be other derivative class
WebData data = new BikeModel();
Webdata data2 = new FooModel();

BikeParser parser = new BikeParser();
FooParser parser2 = new FooParser();

// Should be BikeModel, FooModel
Class<?> returnedtype = parser.GetreturnType();
Class<?> returnedtype2 = parser2.GetreturnType();

// Exporter algorithms wrapper
Exporter exporter = new Exporter();
exporter.SetExporter("BikeExporter",returnedtype);

// Finally export data
exporter.ExportData(data);

// Works too
exporter.SetExporter("FooExporter",returnedtype2);
exporter.ExportData(data2);

实现:

public abstract class WebData { ... }

// Data models
public class BikeModel extends WebData { ... }
public class FooModel extends WebData { ... }

public interface IParser <T extends WebData>
{    
T ParseData();    
Class<T> GetReturnType();
}

// Concrete class
public class BikeParser implements IParser<BikeModel>
{
@Override
public BikeModel ParseData() { ... }

@Override
public Class<BikeModel> GetReturnType()
{
    return BikeModel.class;
}

// interface to export diferent types of data
// BikeModel, FooModel, etc.
public interface IExporter<T extends WebData>
{
    void ExporParts(T data);
}

// Concrete Exporters
public class BikeExporter implements IExporter<BikeModel> { ... }
public class FooExporter implements IExporter<FooModel> { ... }

public class Exporter
{

   private IExporter exporter;

   public void SetExporter(String name, Class<T extends WebData> type)
   {
    exporter = ExporterFactory.GetExporter(name,type)
   }

   public <T extends WebData> void ExporParts(T data)
   {           
      Class<T> c = (Class<T>) data.getClass();        
      exporter.ExporParts(c.cast(data));
   }
}

1 个答案:

答案 0 :(得分:4)

我认为你只是在寻找class literal

@Override
public Class<BikeModel> GetReturnType()
{
    return BikeModel.class;
}