解决方法@H_403_10@
如果所有getter的返回类型相同,则不是很困难.考虑以下PoJo类:
public static class MyPoJo {
final String foo,bar;
public MyPoJo(String foo,String bar) {
this.foo = foo;
this.bar = bar;
}
public String getFoo() {
return foo;
}
public String getBar() {
return bar;
}
public int getBaz() {
return 5;
}
}
然后我们可能有这样的枚举:
public static enum Getters {
FOO(MyPoJo::getFoo),BAR(MyPoJo::getBar);
private final Function<MyPoJo,String> fn;
private Getters(Function<MyPoJo,String> fn) {
this.fn = fn;
}
public String getValue(MyPoJo object) {
return fn.apply(object);
}
}
并像这样使用它:
System.out.println(Getters.FOO.getValue(new MyPoJo("fooValue","barValue"))); // fooValue
但是,如果要返回不同类型,则会出现问题.在这种情况下,我建议使用带有预定义实例的普通类而不是枚举:
public static final class Getters<T> {
public static final Getters<String> FOO = new Getters<>(MyPoJo::getFoo);
public static final Getters<String> BAR = new Getters<>(MyPoJo::getBar);
public static final Getters<Integer> BAZ = new Getters<>(MyPoJo::getBaz);
private final Function<MyPoJo,T> fn;
private Getters(Function<MyPoJo,T> fn) {
this.fn = fn;
}
public T getValue(MyPoJo object) {
return fn.apply(object);
}
}
用法是一样的:
System.out.println(Getters.FOO.getValue(new MyPoJo("fooValue","barValue"))); // fooValue
System.out.println(Getters.BAZ.getValue(new MyPoJo("fooValue","barValue"))); // 5
public static class MyPoJo { final String foo,bar; public MyPoJo(String foo,String bar) { this.foo = foo; this.bar = bar; } public String getFoo() { return foo; } public String getBar() { return bar; } public int getBaz() { return 5; } }
然后我们可能有这样的枚举:
public static enum Getters { FOO(MyPoJo::getFoo),BAR(MyPoJo::getBar); private final Function<MyPoJo,String> fn; private Getters(Function<MyPoJo,String> fn) { this.fn = fn; } public String getValue(MyPoJo object) { return fn.apply(object); } }
并像这样使用它:
System.out.println(Getters.FOO.getValue(new MyPoJo("fooValue","barValue"))); // fooValue
但是,如果要返回不同类型,则会出现问题.在这种情况下,我建议使用带有预定义实例的普通类而不是枚举:
public static final class Getters<T> { public static final Getters<String> FOO = new Getters<>(MyPoJo::getFoo); public static final Getters<String> BAR = new Getters<>(MyPoJo::getBar); public static final Getters<Integer> BAZ = new Getters<>(MyPoJo::getBaz); private final Function<MyPoJo,T> fn; private Getters(Function<MyPoJo,T> fn) { this.fn = fn; } public T getValue(MyPoJo object) { return fn.apply(object); } }
用法是一样的:
System.out.println(Getters.FOO.getValue(new MyPoJo("fooValue","barValue"))); // fooValue System.out.println(Getters.BAZ.getValue(new MyPoJo("fooValue","barValue"))); // 5