我有以下3个测试.前两个工作,最后一个没有.我提出这个问题的动机是,我希望能够抛出对象A,使它与对象具有相同的类B,当A知道它是一个子类型时B.
@Test
public void testWorks() {
Object bar = "foobar";
String blah = (String) bar;
System.out.println(blah); // Outputs foobar
}
@Test
public void testAlsoWorks() {
Object bar = "helloworld";
String blah = String.class.cast(bar);
System.out.println(blah); // Outputs helloworld
}
@Test
public void testfails() {
Object bar = "foobar";
String thetype = "hello";
Class stringclass = thetype.getClass();
String blah = stringclass.cast(bar); // Compiler error: incompatible types: Object cannot be converted to String
System.out.println(blah);
} …Run Code Online (Sandbox Code Playgroud) 我有一个带有List属性的Java AutoValue类.我想允许构建器附加到List而不必传递整个构造的列表.
例:
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class Deck {
public abstract List<Card> cards();
public static Builder builder() {
return new AutoValue_Card.Builder()
.cards(new ArrayList<Card>());
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder cards(List<Card> cards);
/**
* Append card to cards in the constructed Deck.
*/
public Builder addCard(Card card) {
// Is it possible to write this function?
}
}
}
Run Code Online (Sandbox Code Playgroud)
编写addCard函数的最佳解决方案是什么?AutoValue是否已经以某种方式支持此功能?构造类中的中间卡属性对Builder不可见,因此我无法直接访问它.我可以尝试通过在Builder中保留我自己的卡副本来直接绕过Builder,这是唯一的选择吗?