如果这是非常基本的内容,我很抱歉,但我在书籍和搜索中找不到任何内容。我试图在创建对象时发送信息,但有很多选项,我只真正更改一个(不幸的是,它接近尾声)。
假设我有这样的东西:
class_to_start_(int maxActive,
byte whenExhaustedAction,
long maxWait,
int maxIdle,
int minIdle,
boolean testOnBorrow,
boolean testOnReturn,
long timeBetweenEvictionRunsMillis,
int numTestsPerEvictionRun,
long minEvictableIdleTimeMillis,
boolean testWhileIdle,
long softMinEvictableIdleTimeMillis,
boolean lifo)
它们都有默认值,所以我不需要更改它们中的任何一个,但我只想修改最后一个lifo
的默认值。我可以在不向其他人发送值的情况下做到这一点吗?理想情况下类似于 class_to_start_('lifo'=True)
(这不起作用,我尝试过)。
这可能吗?
最佳答案
Java 没有默认参数值,所以简短的回答是否定的。
但是,您可以重载构造函数,这样您就有一个只接受您想要更改的参数的构造函数:
/** Main constructor. */
public Foo(int maxActive,
byte whenExhaustedAction,
int minIdle,
boolean testOnBorrow,
boolean lifo)
/** Convenience constructor. */
public Foo(boolean lifo)
{
this(1, 0x01, 3, false, lifo); // call the main constructor will default values
}
您还可以考虑制作 fluent interface构建器对象。那么你的想法就是:
final Foo f = new FooBuilder().withLifo(false).build();
关于java - 有没有办法将值传递给构造函数中的特定项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10440573/