我以前没有使用过泛型。现在是时候,我应该创建一个泛型类,否则我的代码长度将变得更大并且更难以理解。
这就是将记录插入到位于 Windows Azure 的数据库中的方式:
public class Item {
public int Id;
public String Text;
}
在定义 mClient 的同一 Activity 中,添加以下代码:
Item item = new Item();
item.Text = "Awesome item";
mClient.getTable(Item.class).insert(
item,
new TableOperationCallback<Item>() {
public void onCompleted(
Item entity,
Exception exception,
ServiceFilterResponse response
) {
if (exception == null) {
// Insert succeeded
} else {
// Insert failed
}
}
});
我无法创建通用类来对位于 Windows Azure 的数据库执行操作,例如插入、删除等。
这是 Windows Azure 引用的链接(如果需要):
http://dl.windowsazure.com/androiddocs/
我尝试了以下代码:
public class WindowsAzureOperations<T> {
T mT;
MobileServiceClient mClient;
Context mContext;
public void insert(MobileServiceClient mClient, T tObject, final Context tmpContext) {
this.mClient = mClient;
mT = tObject;
mContext = tmpContext;
this.mClient.getTable(mT.getClass()).insert(mT, // error in this line
new TableOperationCallback<T>() {
public void onCompleted(T entity, Exception exception,
ServiceFilterResponse response) {
if (exception == null) {
} else {
}
}
});
}
}
它显示以下错误:
The method
insert(capture#1-of ? extends Object, TableOperationCallback<capture#1-of ? extends Object>)
in the typeMobileServiceTable<capture#1-of ? extends Object>
is not applicable for the arguments(T, new TableOperationCallback<T>(){})
请帮助我。提前致谢。
最佳答案
问题在于您如何调用 getTable
。给定 Class<T>
,该方法将返回 MobileServiceTable<T>
。但是mT.getClass()
返回 Class<? extends T>
,因为运行时类型为 mT
可能是T
或某种扩展 T
.
作为解决方法,请使用 insert
方法采用 Class<T>
类型的参数:
public void insert(
MobileServiceClient mClient,
T tObject,
Class<T> objectType,
final Context tmpContext
) {
this.mClient = mClient;
mT = tObject;
mContext = tmpContext;
this.mClient.getTable(objectType).insert(
mT,
new TableOperationCallback<T>() {
public void onCompleted(T entity, Exception exception,
ServiceFilterResponse response) {
if (exception == null) {
} else {
}
}
});
}
我还建议您移动 mClient
的分配, mT
,和mContext
到 WindowsAzureOperations
的构造函数。事实上,从表面上看你的类,不需要实例化它 - 只需使用静态通用方法:
public final class WindowsAzureOperations {
// now a utility class so prevent instantiation
private WindowsAzureOperations() { }
public static <T> void insert(
MobileServiceClient mClient,
T tObject,
Class<T> objectType,
final Context tmpContext
) {
mClient.getTable(objectType).insert(
tObject,
new TableOperationCallback<T>() {
@Override
public void onCompleted(
T entity,
Exception exception,
ServiceFilterResponse response
) {
if (exception == null) {
//...
}
else {
//...
}
}
}
);
}
}
关于java - Android:无法创建泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17784767/