简体   繁体   English

如何在运行时获取对象类型?

[英]How to get object type in runtime?

I am trying to create a class that is responsable for managing all the database access of my application, controlling the API of my DAO objects that have all protected methods. 我正在尝试创建一个类,该类负责管理应用程序的所有数据库访问,控制具有所有受保护方法的DAO对象的API。 Some indentifiers are in portuguese since I'm a brazilian, anyways I think you will be able to understand whats going on there.. Following is the code: 由于我是巴西人,所以某些标识符使用葡萄牙语,无论如何,我认为您将能够理解那里的情况。以下是代码:

public class DatabaseManager {

private ItemExpansivelDataSource itemExpansivelDataSource;
private ConfiguracoesDashboardDataSource configuracoesDashboardDataSource;
private PranchaDataSource pranchaDataSource;
private PranchaRaizDataSource pranchaRaizDataSource;

private HashMap<Class<?>, DataSource<?>> dataSourcesMap;

public DatabaseManager() {
    super();
    this.dataSourcesMap = new HashMap<Class<?>, DataSource<?>>();
    dataSourcesMap.put(ItemExpansivel.class, itemExpansivelDataSource);
    dataSourcesMap.put(ConfiguracoesDashboard.class, itemExpansivelDataSource);
    dataSourcesMap.put(Prancha.class, itemExpansivelDataSource);
    dataSourcesMap.put(PranchaRaiz.class, itemExpansivelDataSource);
}

public void insert(Object objeto){
    if(dataSourcesMap.containsKey(objeto.getClass())) {
        return dataSourcesMap.get(objeto.getClass()).insert(objeto);
    } else {
        throw new RuntimeException(ErrorMessages.NAO_EXISTE_DATA_SOURCE.toString());
    }
}

and there is the declaration of my datasource 还有我的数据源的声明

public interface DataSource<T> {

List<T> getAll();
T findById(Integer id);

void openConection();
void closeConection();

void update(T valor);
void update(List<T> valores);

T insert(T valor);
List<T> insert(List<T> valores);

void delete(T valor);
void delete(List<T> valores);

Integer getLastInsertedRowId();
T converter(Cursor cursor);
}

My problem is that java dont know what kind of object it will receive as parameter so I cant call the insert method as I am trying to do, I need to find a work around but I cant think on nothing.. I wish someone can bring me some light, because I really think this is a good aproach to control the API of my DAO objects.. Thanks a lot 我的问题是java不知道它将作为参数接收什么样的对象,因此我无法像尝试做的那样调用insert方法,我需要找到解决方法,但是我什么也没想。给我一些启发,因为我真的认为这是控制DAO对象API的好方法。

The only way to make it type-safe is to add a method to your DataSource interface which returns the required type, ie: 使其成为类型安全的唯一方法是在DataSource interface添加一个返回所需类型的方法,即:

Class<T> getDataType();

Then you can turn your Map operations into type-safe code by introducing a helper method per operation: 然后,您可以通过为每个操作引入帮助器方法,将Map操作转换为类型安全的代码:

public Object insert(Object objeto){
  final DataSource<?> dataSource = dataSourcesMap.get(objeto.getClass());
  if(dataSource!=null) {
      assert dataSource.getDataType().isInstance(objeto);
      return doInsert(dataSource, objeto);
  } else {
     throw new RuntimeException(ErrorMessages.NAO_EXISTE_DATA_SOURCE.toString());
  }
}
private static <T> T doInsert(DataSource<T> ds, Object o) {
  return ds.insert(ds.getDataType().cast(o));
}

The only way without such a method is to work without type safety. 没有这种方法的唯一方法是在没有类型安全的情况下工作。 If your Map is private and you maintain the mappings correctly so that you always have a valid Class -key → value's type parameter relationship this could be an option. 如果您的Map是私有的,并且您正确地维护了映射,以便始终具有有效的Class -key→值的type参数关系,则可以选择此选项。 In this case, use the helper method as above but replace the ds.getDataType().cast(o) by an unsafe type-cast: (T)o . 在这种情况下,请使用上述辅助方法,但用不安全的类型转换(T)o替换ds.getDataType().cast(o)

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

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