我想编写一个具有多个不同类型字段的类,但在任何时候,实例对象的一个且只有一个字段具有非空值。
到目前为止我所做的看起来并不干净。
class ExclusiveField {
private BigInteger numericParam;
private String stringParam;
private LocalDateTime dateParam;
public void setNumericParam(BigInteger numericParam) {
unsetAll();
this.numericParam = Objects.requireNonNull(numericParam);
}
public void setStringParam(String stringParam) {
unsetAll();
this.stringParam = Objects.requireNonNull(stringParam);
}
public void setDateParam(LocalDateTime dateParam) {
unsetAll();
this.dateParam = Objects.requireNonNull(dateParam);
}
private void unsetAll() {
this.numericParam = null;
this.stringParam = null;
this.dateParam = null;
}
}
Java 是否以某种方式支持这种模式,还是有更体面的方法来实现它?
最佳答案
对象只有一个非null 字段的最简单方法是,实际上只有一个字段,并隐式假设所有其他字段为null。您只需要另一个标签字段,即可确定哪个字段是非null。
由于在您的示例中,所有替代方案似乎都与值的类型有关,类型本身可能是标记值,例如
class ExclusiveField {
private Class<?> type;
private Object value;
private <T> void set(Class<T> t, T v) {
value = Objects.requireNonNull(v);
type = t;
}
private <T> T get(Class<T> t) {
return type == t? t.cast(value): null;
}
public void setNumericParam(BigInteger numericParam) {
set(BigInteger.class, numericParam);
}
public BigInteger getNumericParam() {
return get(BigInteger.class);
}
public void setStringParam(String stringParam) {
set(String.class, stringParam);
}
public String getStringParam() {
return get(String.class);
}
public void setDateParam(LocalDateTime dateParam) {
set(LocalDateTime.class, dateParam);
}
public LocalDateTime getDateParam() {
return get(LocalDateTime.class);
}
}
如果类型不是唯一的区别,您需要定义不同的键值。 enum 将是一个自然的选择,但不幸的是,enum 常量不能提供类型安全。所以,替代方案看起来像:
class ExclusiveField {
private static final class Key<T> {
static final Key<String> STRING_PROPERTY_1 = new Key<>();
static final Key<String> STRING_PROPERTY_2 = new Key<>();
static final Key<BigInteger> BIGINT_PROPERTY = new Key<>();
static final Key<LocalDateTime> DATE_PROPERTY = new Key<>();
}
private Key<?> type;
private Object value;
private <T> void set(Key<T> t, T v) {
value = Objects.requireNonNull(v);
type = t;
}
@SuppressWarnings("unchecked") // works if only set() and get() are used
private <T> T get(Key<T> t) {
return type == t? (T)value: null;
}
public void setNumericParam(BigInteger numericParam) {
set(Key.BIGINT_PROPERTY, numericParam);
}
public BigInteger getNumericParam() {
return get(Key.BIGINT_PROPERTY);
}
public void setString1Param(String stringParam) {
set(Key.STRING_PROPERTY_1, stringParam);
}
public String getString1Param() {
return get(Key.STRING_PROPERTY_1);
}
public void setString2Param(String stringParam) {
set(Key.STRING_PROPERTY_2, stringParam);
}
public String getString2Param() {
return get(Key.STRING_PROPERTY_2);
}
public void setDateParam(LocalDateTime dateParam) {
set(Key.DATE_PROPERTY, dateParam);
}
public LocalDateTime getDateParam() {
return get(Key.DATE_PROPERTY);
}
}
关于java - 什么是在对象中只允许一个非空字段的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56037079/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta