[英]Java Immutables Library: Check if all Optionals are empty?
I'd like to determine whether all Optional
members of an immutable are empty. 我想确定一个不可变的所有
Optional
成员是否为空。 Is there a way to do this automatically without checking all the known Optionals by hand? 有没有办法自动执行此操作而无需手动检查所有已知的Optionals?
I'm concerned that even if do write a check for each Optional member someone will come along later and add an Optional field without updating that method. 我担心即使为每个可选成员写一个支票,有人会稍后再来,并添加一个可选字段而不更新该方法。
It may change in the future, but I think you can try take a look at the overloaded builder methods generated for optional members: 它可能会在将来发生变化,但我认为您可以尝试查看为可选成员生成的重载构建器方法:
For an optional attribute named
opt
, where elements are of typeT
对于名为
opt
的可选属性,其中元素的类型为T
opt(T)
sets present value forT
opt(T)
设定为当前值T
opt(Optional<T>)
specifies present or absentopt(Optional<T>)
指定存在或不存在
SomeValue.java SomeValue.java
@Value.Immutable
public abstract class SomeValue {
public abstract int foo();
public abstract Optional<Object> obj();
public abstract com.google.common.base.Optional<Double> d();
}
TestImmutables.java TestImmutables.java
public class TestImmutables {
public static void main(String [] args) {
SomeValue someValue = ImmutableSomeValue.builder().foo(2).build();
for (Method method : someValue.getClass().getDeclaredMethods()) {
System.out.print(method.getName() + "(");
for (Type t : method.getGenericParameterTypes()) {
System.out.print(t);
System.out.print(",");
}
System.out.println(")");
}
}
}
Output 产量
Each line is a method, pay attention to the methods generated for optional members. 每一行都是一个方法,注意为可选成员生成的方法。
builder()
equalTo(class immutables.ImmutableSomeValue,)
withObj(class java.lang.Object,) < obj
withObj(java.util.Optional<java.lang.Object>,) < obj
withD(com.google.common.base.Optional<java.lang.Double>,) < d
withD(double,) < d
d()
withFoo(int,)
foo()
obj()
equals(class java.lang.Object,)
toString()
hashCode()
copyOf(class immutables.SomeValue,)
Basically you are looking for two overloads, each with exactly one parameter, and if parameter type of one is T
, the parameter type of the other is SomeOptional<T>
. 基本上你正在寻找两个重载,每个具有正好一个参数,而且如果参数类型之一是
T
,参数类型的其他的是SomeOptional<T>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.