首页 > 解决方案 > 铸造泛型类

问题描述

我将一个对象传递给将其作为泛型类的函数。

public void insertToDB(T t) {
        String tableName = DynamoDBMapperConfig.DefaultTableNameResolver.INSTANCE.getTableName(t.getClass(), mapperConfig);
        itemValues = addData(tableName, t.getClass());
    }

现在,我检查了 t.getClass() 是否返回了正确的类。我正在尝试将数据添加到具有以下声明的 DynamoDB 中。

@DynamoDBTable(tableName = "table")
public class SomeClass {
    @DynamoDBHashKey(attributeName="id")
    public String id;

    @DynamoDBAttribute(attributeName="createTime")
    public Date createTime;
    public void setCreateTime(Date createTime){
        this.createTime = createTime;
    }
}

采用 tableName 和泛型类定义的 addData() 如下:我采用泛型类,因为这个函数将被称为我的多个 DynamoDB,因此我想保持它是通用的。基于tableName我会调用具体的函数来添加数据。

private HashMap<String, AttributeValue> addData(String tableName, Class<?> tClass){
        if (tableName.equalsIgnoreCase("table"))
            itemValues = add(....?);
// Unable to find what to pass in add() so that it can be of type SomeClass with preset values which were set before the `insertToDB() `
        return itemValues;
    }

private HashMap<String, AttributeValue> add(SomeClass someClass){
        addMapStringEntry(itemValues, "id", someClass.id);
        addMapStringEntry(itemValues, "createTime", someClass.createTime.toString()); // converting to string
        return itemValues;
    }

我的问题是,我应该传入什么add()以便实际定义可以采用somClass. 我尝试通过,tClass但即使它给出了正确的类名someClass,它也在抱怨所需类型:someClass并且提供的是 `Class <?>

标签: javaamazon-web-servicesamazon-dynamodb

解决方案


推荐阅读