Java。工厂创建应该 return 通用 class
Java. Factory creation should return Generic class
有人可以帮忙吗。
我想创建一个工厂,它将 return 具体 class。
线路有问题 - filterFactory.getFilter(myColumn.getType()).setMin(5);
出现错误:无法在 'Object'
中解析方法 'setMin'
public enum Columns {
Name(ColumnType.String),
Age(ColumnType.Numeric);
private final ColumnType type;
Columns(ColumnType type) {
this.type = type;
}
public ColumnType getType() {
return type;
}
}
public enum ColumnType {
String,
Numeric
}
public class NumericFilter extends ColumnFilter {
public void setMin(int min) {
System.out.println("min is set" + min);
}
}
public class StringFilter extends ColumnFilter {
public void setFilter(String filter) {
System.out.println("filter is set to:" + filter);
}
}
public class ColumnFilterFactory {
public <T> T getFilter(ColumnType type) {
if (type == null) {
return null;
}
if (type == ColumnType.String) {
return (T) new StringFilter();
} else if (type == ColumnType.Numeric) {
return (T) new NumericFilter();
}
return null;
}
}
public class BasicTest {
public static void main(String[] args) {
Columns myColumn = Columns.Age;
ColumnFilterFactory filterFactory = new ColumnFilterFactory();
filterFactory.getFilter(myColumn.getType()).setMin(5);
}
}
编译器无法知道工厂将成为什么类型 return,因此您需要给它一点帮助。例如通过使用中间变量:
NumericFilter nf = filterFactory.getFilter(myColumn.getType());
nf.setMin(5);
有人可以帮忙吗。
我想创建一个工厂,它将 return 具体 class。
线路有问题 - filterFactory.getFilter(myColumn.getType()).setMin(5);
出现错误:无法在 'Object'
public enum Columns {
Name(ColumnType.String),
Age(ColumnType.Numeric);
private final ColumnType type;
Columns(ColumnType type) {
this.type = type;
}
public ColumnType getType() {
return type;
}
}
public enum ColumnType {
String,
Numeric
}
public class NumericFilter extends ColumnFilter {
public void setMin(int min) {
System.out.println("min is set" + min);
}
}
public class StringFilter extends ColumnFilter {
public void setFilter(String filter) {
System.out.println("filter is set to:" + filter);
}
}
public class ColumnFilterFactory {
public <T> T getFilter(ColumnType type) {
if (type == null) {
return null;
}
if (type == ColumnType.String) {
return (T) new StringFilter();
} else if (type == ColumnType.Numeric) {
return (T) new NumericFilter();
}
return null;
}
}
public class BasicTest {
public static void main(String[] args) {
Columns myColumn = Columns.Age;
ColumnFilterFactory filterFactory = new ColumnFilterFactory();
filterFactory.getFilter(myColumn.getType()).setMin(5);
}
}
编译器无法知道工厂将成为什么类型 return,因此您需要给它一点帮助。例如通过使用中间变量:
NumericFilter nf = filterFactory.getFilter(myColumn.getType());
nf.setMin(5);