[英]Combine two methods using generics
I have two different boolean variables that are set very similarly and I want to create a generic method that can handle two different class objects as the argument. 我有两个设置非常相似的布尔变量,我想创建一个通用方法,该方法可以处理两个不同的类对象作为参数。
Note: Area and HuntingField are two entities I've created using ebean. 注意:Area和HuntingField是我使用ebean创建的两个实体。
Currently this is what I do in order to set the two booleans: 目前,这是我要设置两个布尔值的操作:
boolean isNewArea = (Area.find.where().eq("id", area.id)
.findRowCount() == 1) ? false : true;
if (isNewArea) {
area.save();
}
boolean isNewHuntingField = (HuntingField.find.where()
.eq("id", hf.id).findRowCount() == 1) ? false : true;
if (isNewHuntingField) {
hf.save();
These are the two different find methods defined in the corresponding classes: 这是在相应类中定义的两种不同的find方法:
public static Finder<String, HuntingField> find = new Finder<String, HuntingField>(
String.class, HuntingField.class);
public static HuntingField find(String searchString) {
return find.where().eq("id", searchString).findUnique();
}
and this: 和这个:
public static Finder<String, Area> find = new Finder<String, Area>(
String.class, Area.class);
public static Area find(String searchString) {
return find.where().eq("id", searchString).findUnique();
}
Now I want to create a method that takes either a HuntingField type object or an Area type object as a parameter and uses the corresponding find method on that object and returns a boolean value: 现在,我想创建一个将HuntingField类型的对象或Area类型的对象作为参数,并在该对象上使用相应的find方法并返回布尔值的方法:
public static <T> boolean alreadyExist(Class<T> obj){
boolean isNewArea = (obj.find.where().eq("id", obj.id)
.findRowCount() == 1) ? false : true;
But eclipse is telling me that find and id cannot be resolved or is not a field. 但是eclipse告诉我,find和id无法解析或不是字段。
What am I doing wrong? 我究竟做错了什么?
You are mistaking the class for the finder. 您把学习者的课程弄错了。
public static <T> boolean alreadyExist(Finder<String, T> obj){
boolean isNew = (obj.find.where().eq("id", obj.id)
.findRowCount() == 1) ? false : true;
boolean huntingFieldExists = alreadyExist(new Finder<String, HuntingField>());
boolean areaExists = alreadyExist(new Finder<String, Area>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.