请问C# [Optional, Defaultjsp parammeterValue(jsp paramm)]是什么意思?

Keyboard Shortcuts?
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search(current page)
Focus search box
Change language:
Brazilian Portuguese
Chinese (Simplified)
ReflectionParameter::getDefaultValue
ReflectionParameter::getDefaultValue & Gets default parameter value
Description
ReflectionParameter::getDefaultValue
Parameters
This function has no parameters.
Return Values
The parameters default value.
Example #1 Getting
&?phpfunction&foo($test,&$bar&=&'baz'){&&&&echo&$test&.&$bar;}$function&=&new&ReflectionFunction('foo');foreach&($function-&getParameters()&as&$param)&{&&&&echo&'Name:&'&.&$param-&getName()&.&PHP_EOL;&&&&if&($param-&isOptional())&{&&&&&&&&echo&'Default&value:&'&.&$param-&getDefaultValue()&.&PHP_EOL;&&&&}&&&&echo&PHP_EOL;}?&
The above example will output:
Name: test
Default value: baz
Due to implementation details, it is not possible to get the default value
of built-in functions or methods of built-in classes. Trying to do this will
being thrown.
- Checks if optional
- Checks if passed by reference
[Editor's note: fixed on user's request]
Getting `Uncaught ReflectionException: Internal error: Failed to retrieve the default value`?
You have to wrap this inside -&isDefaultValueAvailable().中提到了&可选参数&这个C# 4.0中新增的语言特性,但是写过之后还是不满足,心里还是有一些疑问没有得到解释。于是又做了一些探索,过程中竟然发现这么一个小小的语言特性背后隐藏着的有趣问题还真不少。这次就把探索过程中的发现和疑问记录下来。
&可选参数&的实现
Cnblogs上有一篇中提到一句:&缺省参数最终体现为两个特殊的自定义特性OptionalAttribute和DefaultParameterValueAttribute &。为了验证这个说法的正确性,我自己做了一些试验。
要研究语言特性的实现原理最好的方法莫过于反编译出IL代码来一探究竟了。所以,那就顺着这条线索走吧。
首先用C#代码写一个很简单的测试方法:
public void TestMethod(string str = "A")
中提到过这种写法跟直接使用OptionalAttribute和DefaultValueAttribute这两个attribute的效果是一样的。
public void TestMethodWithAttributes([Optional, DefaultParameterValue("A")]string str)
这两段代码编译出来的IL除了名字之外别无二致,下面就以第一个方法为例,它的IL是这样的:
.method public hidebysig instance void
TestMethod([opt] string str) cil managed
.param [1] = "A"
// Code size
} // end of method Program::TestMethod
同时其生成的Metadata是这样的:
MethodName: TestMethod ()
: [Public] [HideBySig] [ReuseSlot]
: 0x0000205b
ImplFlags : [IL] [Managed]
CallCnvntn: [DEFAULT]
ReturnType: Void
1 Arguments
Argument #1:
1 Parameters
(1) ParamToken : () Name : str flags: [Optional] [HasDefault]
() Default: (String)
说老实话,上面这两段&天书&我并没有完全读懂,但是还是发现有一些异常,觉得有些东西不太对头,为什么这么说呢?因为一般的attribute编译之后的结果通常不是这样的。比如下面这个例子:
先自定义一个只能应用到参数上的attribute:
[AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = true)]
sealed class MyAttribute : Attribute
然后定义一个被该attribute修饰的方法:
public void TestAttribute([My]string str)
这个方法编译之后的IL如下:
.method public hidebysig instance void
TestAttribute(string str) cil managed
.param [1]
.custom instance void HowDidTheyImplementOptionalParameters.MyAttribute::.ctor() = ( 01 00 00 00 )
// Code size
} // end of method Program::TestAttribute
可以看到上面代码中标红的部分是TestMethod的IL中没有的。而且,它的Metadata和TestMethod的也是不同的:
MethodName: TestAttribute ()
: [Public] [HideBySig] [ReuseSlot]
ImplFlags : [IL] [Managed]
CallCnvntn: [DEFAULT]
ReturnType: Void
1 Arguments
Argument #1:
1 Parameters
(1) ParamToken : () Name : str flags: [none] ()
CustomAttribute #1 (0c000010)
-------------------------------------------------------
CustomAttribute Type:
CustomAttributeName: HowDidTheyImplementOptionalParameters.MyAttribute :: instance void .ctor()
Value : 01 00 00 00
ctor args: ()
这个方法的Metadata的最后多了一段CustomAttribute的描述,其flags也为空,不像TestMethod的flags后面跟有[Optional] [HasDefault]这样的标志。
因为我没有读过的文档,所以下面只是做一个不太谨慎的推测:OptionalAttribute和DefaultParameterValueAttribute这两个attribute和其他的attribute不同,他们有自己对应的专有的flags。调用TestMethod的代码在被编译时,编译器会去读取存储于元数据中的默认值,并把读取到的值嵌入到IL中去。
由于在TestMethod的C#代码中、编译出的IL代码中,及其元数据中都不见OptionalAttribute和DefaultParameterValueAttribute 的踪迹,所以我认为&缺省参数最终体现为两个特殊的自定义特性OptionalAttribute和DefaultParameterValueAttribute &这种说法是有待商榷的。
背后的陷阱
&可选参数&看起来方便又好用,但是使用它是不是真的是多快好省的绝佳选择呢?实际上不是的,它的背后隐藏着至少两个陷阱(我只发现了两个)。
第一个陷阱:版本更迭的问题
就以上面提到的TestMethod为例,写一个方法来调用它:
public void Caller()
TestMethod();
这里在调用时没有传入参数,也就是说相当于传入了默认的参数&A&。Caller编译出来的IL是这样的:
.method public hidebysig instance void
Caller() cil managed
// Code size
instance void HowDidTheyImplementOptionalParameters.Program::TestMethod(string)
} // end of method Program::Caller
请注意标红的两行,Caller的IL中实际是把&A&这个值写死了的。也就是说如果有一个包含&可选参数&的非强命名程序集在版本升级时修改了参数的默认值,其他引用它的程序集如果没有重新编译就无法获得到新的默认参数值,在运行时仍然会传入老版本中定义的值。
第二个陷阱:跨语言调用
并不是所有的语言都被强制要求支持&可选参数&这一特性。对于不支持这一特性的语言来说,完全可以忽略掉元数据中包含的默认值而强制要求这一语言的用户去显式的提供参数值。而这样就会导致代码的运行时行为不一致。
C#4.0之前都所有版本都是不支持&可选参数&的。也就是说如果在VS2010中用C#4.0的语法和.NET Framework 2.0的框架编一个含有&可选参数&的程序集,然后在VS2008中的项目中引用这个程序集的话,则只能显式的提供参数值。
针对以上两点,我觉得在使用&可选参数&时应该遵循以下的原则:在public API(包括公开类型的公开成员和公开类型的受保护成员)中尽量不要用&可选参数&,而是使用方法重载,以避免API行为不一致。在程序集内部的私有API中,尽情享用吧。
关于CLS-Compliant
的文档中提到说&可选参数&不是CLS-Compliant的。我觉得这种说法是错误的。最简单的验证方式就是加上CLSCompliantAttribute来试试看。
在含有TestMethod(这里要保证TestMethod是公开类型中的公开方法,因为CLSCompliant只针对public API)的项目的AssemblyInfo.cs中加上这么一行:
[assembly: CLSCompliant(true)]
然后编译,编译器没有给出任何警告。而如果是在public API中使用了unit这一&臭名昭著&的类型的话,编译器会毫不犹豫的给出一个警告。比如这样的一个方法:
public void TestCLSCompliant(uint parameter)
在编译时就会得到一个警告:Argument type 'uint' is not CLS-compliant。
而且中也提到了虽然&可选参数&没有被收录到CLS的规范中,但是CLS是可以&容忍&它的存在的。
Reflector中可能的Bug
以上所有反编译都是用IL Dasm来做的,而如果用最新版的Reflector(就是只能试用14天的那个版本)来查看反编译出的C#(把版本设为任何非None的值)代码的话,会发现它会把TestMethod解释为使用了OptionalAttribute和DefaultParameterValueAttribute。我怀疑这是因为无论是使用&可选参数&还是直接使用OptionalAttribute和DefaultParameterValueAttribute,编译出的结果都是一样的,Reflector无从判断源代码中使用的是哪一种,索性就假定为是第二种了。
虽然OptionalAttribute没有出现在TestMethod的C#代码中,在编译出来的IL和元数据中也不见踪影,但是它还是出现在了编译出的程序集的TypeRefs中,而DefaultValueAttribute却没有出现。这是为什么呢?
MSDN上的:
StackOverflow上的:
请问CSDN的工作人员一个问题,为什么用Live Writer发布的文章一开始排版,格式都是正确的,只要在CSDN的Web Editor里面编辑一次就全乱了呢?
本文已收录于以下专栏:
相关文章推荐
uploadify插件可选参数的详细介绍博客分类:
JAVA、WEB开发 ·概述 Uploadify 是一个JQuery插件,它协助你轻松简单的将一个或多个文件上传至你的网站。 它需要Flash控...
JavaScript函数可以以任意数目的参数来调用, 而不管函数定义中的参数名字有多少个。由于函数是宽松类型的,它就没有办法声明所期望的参数的类型,并且,向任何函数传递任意类型的参数都是合法的。
VB.NET作为一款真正的面向对象语言,其功能非常强大,可以支持继承,并能进行代码托管等等。在这里我们先来了解一下VB.NET可选参数的一些应用技巧,希望能帮助大家了解这一编程语言的基本应用方法。.n...
编辑日志:
160508创建
160530优化添加:显式传参
160916SQL语句高亮显示、格式优化
可选参数的存在,可以极大的降低代码的重复冗余。在数据库开发中,也是如此。现在针对MSSQL...
execCommand 方法通常用于控制可编辑的 IFRAME 内容,制作富文本编辑器。 但他现在为止还是非标准的,方法的首参数 Commmands 的可选值由各个浏览器厂商制定,支持程度并不统一。...
有时候需要在程序中查找某一目录下的某一类文件,例如需要在E:\data\file_selector_test 目录下面查找所有已.java为后缀名的文件。其实这个功能自己也可以实现,很简单,只需要遍历...
execCommand 方法通常用于控制可编辑的 IFRAME 内容,制作富文本编辑器。 但他现在为止还是非标准的,方法的首参数 Commmands 的可选值由各个浏览...
可选参数有一些注意点:
1.可选参数一定程度上解脱了一些情况下必须重载的需求。
2.可选参数一定要放在所有的参数最后。
3.可选参数可以有多个,但都必须排列放在所有参数的最后。
4.方法的所有参数都可...
他的最新文章
讲师:李江龙
讲师:司徒正美
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)Posts - 136,
Articles - 0,
Comments - 63
21:42 by cnb_mtime, ... 阅读,
编辑器加载中...
就像默认的路由配置, 我们可以指定默认值UrlParameter.Optional.
routes.MapRoute(null, "Catalog/{page}",
new { controller = "Products", action = "List", page = UrlParameter.Optional });
这样, 当访问的URL有page值的时候, 我们就采用传入的vallue, 如果没有, 那么我们就不想action方法中传任何参数.你可能会疑惑, 为什么不用0或者是null 作为默认参数, 下面是它的两个原因:
If your action method takes a page parameter of type int, then because that type can&t hold null, you would have to supply the default value of 0 or some other int value. This means the action method would now always receive a legal value for page, so you wouldn&t be able to control the default value&using the MVC Framework&s [DefaultValue] attribute or C# 4&s optional parameter syntax on the action method itself (you&ll learn more about these in the&next chapter).
如果你的action方法有个int类型的page参数,但是它是值类型, 不能是null. 所以你需要提供一个默认值(0或者是其他的值). 这也以为着action方法总是需要一个合法的值, 所以, 如果action方法自身使用mvc框架的[defaultvalue]特性或者是C#4的可选参数语法, 你将无法控制它的类型.(你会在接下来的一章中了解更多)
Even if your action&s page parameter was nullable, there&s a further limitation. When binding incoming data to action method parameters, the MVC Framework prioritizes routing parameter values above query string values (you&ll learn more about value providers and model binding in Chapter 12). So, any routing value for page&even if it&s null&would take priority and hide any query string value called page.
即时你的action的page参数可以是null类型. 这里还有个限制. 当action方法的参数是binding类型的时候, mvc 框架会将路由参数优先于查询字符串值.(你会在12章中学到值提供者和模型绑定). 所以, 任何为page设置的路由值--即使是null--也会优先于访问page的查询字符串
UrlParameter.Optional解决了这两个问题1、CLR根本不知道&命名空间&(Namespace)这回事
C#编译器编译你的代码时,会自动把命名空间名称和类型名称拼到一起,形成类型全名(Full name,如:&System.IO&+&FileStream&形成&System.IO.FileStream&)。CLR对此一无所知,他看到的永远都是类型全名,并认为类型名称理应如此。
C#引入命名空间只是为了让你少打几个字,不必每次都繁琐地写下一个类型的完整名称。另外,命名空间还是一种对类型进行逻辑分类的方法(让相似功能或用途的类型在同一个命名空间内)。
但是,请记住,命名空间名称与程序集(Assembly)名称没有半点关系,虽然大多数程序集(尤其是FCL中)的名称里都包含了命名空间,但这只是一种习惯,并不是一种标准,一个程序集内可能包含多个命名空间,一个命名空间也可能存在于多个程序集内。
2、CLR不知道什么叫&可选参数&(Optional Parameter)
当C#编译器发现你为一个方法的参数设定了一个默认值时,他会&偷偷地&在参数上做上些标记(自动增加两个特性:System.Runtime.InteropServices.OptionalAttribute和System.Runtime.InteropServices.DefaultParameterValueAttribute),并在编译时为其生成特殊元数据(你所设定的默认值也将以常量的形式存于元数据中)。当该方法被调用时,如果传递的参数省略了这个可选参数,C#编译器会从元数据中取出默认值,自动为你补全参数。对于上述整个过程,CLR全然不知。
3、CLR&不知有var,无论dynamic&
详见一文。
4、CLR认为ref和out没有区别
C#编译器会为ref和out生成完全相同的元数据,所以在CLR看来他们没有区别。相反,C#编译器对开发者则比较&苛刻&。他让我们区分ref和out,其实是希望我们能够显式地表明我们的意图:参数会在方法外被初始化(ref)还是在方法内被初始化(out)。当C#编译器通过ref或out窥探到我们的意图后,便可据此完成语法检测,以保证参数确实在我们所设想的地方完成初始化。
顺便说一下,CLR允许基于方法参数是否使用了ref和out来进行方法重载(Overload),例如:
public sealed class Point {
static void Add(Point p) { }
static void Add(ref Point p) { }
但不允许重载方法时仅通过ref和out区分,例如:
// 编译出错
public sealed class Point {
static void Add(ref Point p) { }
static void Add(out Point p) { }
原因很简单:CLR认为ref和out是一回事。
5、CLR不认识params关键字
C#向我们承诺,只要声明方法参数时使用了params关键字,以后就可以向该方法传递无限数量的参数。String类型的Format静态方法就是这方面的典型应用。但是,CLR根本就不认得params这个词,更不可能允许一个方法接受无限多个参数。
事实上,当C#编译器发现我们声明方法参数时使用了params关键字后,他将自动为此参数添加一个System.ParamArrayAttribute特性。当此方法被调用时,C#编译器会将以逗号分隔的参数序列打包为一个数组后传给该方法。CLR对此过程一无所知,只知道一个带有数组参数的方法被调用了。
6、(待续)
阅读(...) 评论()methods - Does Java support default parameter values? - Stack Overflow
Join Stack Overflow to learn, share knowledge, and build your career.
or sign in with
I came across some Java code that had the following structure:
public MyParameterizedFunction(String param1, int param2)
this(param1, param2, false);
public MyParameterizedFunction(String param1, int param2, boolean param3)
//use all three parameters here
I know that in C++ I can assign a parameter a default value.
For example:
void MyParameterizedFunction(String param1, int param2, bool param3=false);
Does Java support this kind of syntax?
Are there any reasons why this two step syntax is preferable?
4,904143658
7,02671511
No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).
For constructors,
Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.
11.5k1779106
17.1k22537
No, but you can use the , as described in .
As described in the linked answer, the Builder Pattern lets you write code like
Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
.name("Spicoli")
.motto("Aloha, Mr Hand")
.buildStudent();
in which some fields can have default values or otherwise be optional.
101k53185239
There are several ways to simulate default parameters in Java:
Method overloading.
void foo(String a, Integer b) {
void foo(String a) {
foo(a, 0); // here, 0 is a default value for b
foo("a", 2);
One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted.
a) All optional parameters are of the same type:
void foo(String a, Integer... b) {
Integer b1 = b.length & 0 ? b[0] : 0;
Integer b2 = b.length & 1 ? b[1] : 0;
foo("a", 1, 2);
b) Types of optional parameters may be different:
void foo(String a, Object... b) {
Integer b1 = 0;
String b2 = "";
if (b.length & 0) {
if (!(b[0] instanceof Integer)) {
throw new IllegalArgumentException("...");
b1 = (Integer)b[0];
if (b.length & 1) {
if (!(b[1] instanceof String)) {
throw new IllegalArgumentException("...");
b2 = (String)b[1];
foo("a", 1);
foo("a", 1, "b2");
The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Furthermore, if each parameter has different meaning you need some way to distinguish them.
Nulls. To address the limitations of the previous approaches you can allow null values and then analyse each parameter in a method body:
void foo(String a, Integer b, Integer c) {
b = b != null ? b : 0;
c = c != null ? c : 0;
foo("a", null, 2);
Now all arguments values must be provided, but the default ones may be null.
Optional class. This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value:
void foo(String a, Optional&Integer& bOpt) {
Integer b = bOpt.isPresent() ? bOpt.get() : 0;
foo("a", Optional.of(2));
foo("a", Optional.&Integer&absent());
Optional makes a method contract explicit for a caller, however, one may find such signature too verbose.
Builder pattern. The builder pattern is used for constructors and is implemented by introducing a separate Builder class:
class Foo {
private final S
private final I
Foo(String a, Integer b) {
class FooBuilder {
private String a = "";
private Integer b = 0;
FooBuilder setA(String a) {
FooBuilder setB(Integer b) {
Foo build() {
return new Foo(a, b);
Foo foo = new FooBuilder().setA("a").build();
Maps. When the number of parameters is too large and for most of them default values are usually used, you can pass method arguments as a map of their names/values:
void foo(Map&String, Object& parameters) {
String a = "";
Integer b = 0;
if (parameters.containsKey("a")) {
if (!(parameters.get("a") instanceof Integer)) {
throw new IllegalArgumentException("...");
a = (String)parameters.get("a");
if (parameters.containsKey("b")) {
foo(ImmutableMap.&String, Object&of(
"d", "value"));
Please note that you can combine any of these approaches to achieve a desirable result.
56.6k15119101
Sadly, no.
8,74282941
Unfortunately, yes.
void MyParameterizedFunction(String param1, int param2, bool param3=false) {}
could be written in Java 1.5 as:
void MyParameterizedFunction(String param1, int param2, Boolean... params) {
assert params.length &= 1;
bool param3 = params.length & 0 ? params[0].booleanValue() :
But whether or not you should depend on how you feel about the compiler generating a
new Boolean[]{}
for each call.
For multiple defaultable parameters:
void MyParameterizedFunction(String param1, int param2, bool param3=false, int param4=42) {}
could be written in Java 1.5 as:
void MyParameterizedFunction(String param1, int param2, Object... p) {
int l = p.
assert l &= 2;
assert l & 1 || Boolean.class.isInstance(p[0]);
assert l & 2 || Integer.class.isInstance(p[1]);
bool param3 = l & 0 && p[0] != null ? ((Boolean)p[0]).booleanValue() :
int param4 = l & 1 && p[1] != null ? ((Integer)p[1]).intValue() : 42;
This matches C++ syntax, which only allows defaulted parameters at the end of the parameter list.
Beyond syntax, there is a difference where this has run time type checking for passed defaultable parameters and C++ type checks them during compile.
No, but you can very easily emulate them. What in C++ was:
public: void myFunction(int a, int b=5, string c="test") { ... }
In Java, it will be an overloaded function:
public void myFunction(int a, int b, string c) { ... }
public void myFunction(int a, int b) {
myFunction(a, b, "test");
public void myFunction(int a) {
myFunction(a, 5);
Earlier was mentioned, that default parameters caused ambiguous cases in function overloading. That is simply not true, we can see in the case of the C++: yes, maybe it can create ambiguous cases, but these problem can be easily handled. It simply wasn't developed in Java, probably because the creators wanted a much simpler language as C++ was - if they had right, is another question. But most of us don't think he uses Java because of its simplicity.
4,904143658
You can do this is in Scala, which runs on the JVM and is compatible with Java programs.
class Foo(var prime: Boolean = false, val rib: String)
50.7k9144189
I might be stating the obvious here but why not simply implement the "default" parameter yourself?
public class Foo() {
public void func(String s){
func(s, true);
public void func(String s, boolean b){
//your code here
for the default you would ether use
func("my string");
and if you wouldn't like to use the default, you would use
func("my string", false);
No. In general Java doesn't have much (any) syntactic sugar, since they tried to make a simple language.
2,77622032
You can achieve the same behavior by passing an Object which has smart defaults. But again it depends what your case is at hand.
11.5k1779106
2,35121421
It is not supported but there are several options like using parameter object pattern with some syntax sugar:
public class Foo() {
private static class ParameterObject {
int param1 = 1;
String param2 = "";
public static void main(String[] args) {
new Foo().myMethod(new ParameterObject() {{ param1 = 10; param2 = "bar";}});
private void myMethod(ParameterObject po) {
In this sample we construct ParameterObject with default values and override them in class instance initialization section { param1 = 10; param2 = "bar";}
6,52533043
Try this solution:
public int getScore(int score, Integer... bonus)
if(bonus.length & 0)
return score + bonus[0];
3,36452346
There are half a dozen or better issues such as this, eventually you arrive at the static factory pattern ... see the crypto api for that. Sort difficult to explain, but think of it this way: If you have a constructor, default or otherwise, the only way to propagate state beyond the curly braces is either to have a Boolean isV ( along with the null as default value v failed constructor ) or throw an exception which is never informative when getting it back from field users.
Code Correct be damned, I write thousand line constructors and do what I need. I find using isValid at object construction - in other words, two line constructors - but for some reason I am migrating to the static factory pattern. I just seems you can do a lot if you in a method call, there are still sync() issues but defaults can be 'substituted' better ( safer )
I think what we need to do here is address the issue of null as default value vis-a-vis something String one=new String(""); as a member variable, then doing a check for null before assigning string passed to the constructor.
Very remarkable the amount of raw, stratospheric computer science done in Java.
C++ and so on has vendor libs, yes. Java can outrun them on large scale servers due to it's massive toolbox. Study static initializer blocks, stay with us.
A similar approach to
that works in Java 8 is to use an interface with default getters. This will be more whitespace verbose, but is mockable, and it's great for when you have a bunch of instances where you actually want to draw attention to the parameters.
public class Foo() {
public interface Parameters {
String getRequired();
default int getOptionalInt(){ return 23; }
default String getOptionalString(){ return "Skidoo"; }
public Foo(Parameters parameters){
public static void baz() {
final Foo foo = new Foo(new Person() {
@Override public String getRequired(){ return "blahblahblah"; }
@Override public int getOptionalInt(){ return 43; }
NO, But we have alternative in the form of function overloading.
called when no parameter passed
void operation(){
int a = 0;
int b = 0;
called when "a" parameter was passed
void operation(int a){
int b = 0;
called when parameter b passed
void operation(int a , int b){
This is how I did it ... it's not as convenient perhaps as having an 'optional argument' against your defined parameter, but it gets the job done:
public void postUserMessage(String s,boolean wipeClean)
if(wipeClean)
userInformation.setText(s + "\n");
postUserMessage(s);
public void postUserMessage(String s)
userInformation.appendText(s + "\n");
Notice I can invoke the same method name with either just a string or I can invoke it with a string and a boolean value. In this case, setting wipeClean to true will replace all of the text in my TextArea with the provided string. Setting wipeClean to false or leaving it out all together simply appends the provided text to the TextArea.
Also notice I am not repeating code in the two methods, I am merely adding the functionality of being able to reset the TextArea by creating a new method with the same name only with the added boolean.
I actually think this is a little cleaner than if Java provided an 'optional argument' for our parameters since we would need to then code for default values etc. In this example, I don't need to worry about any of that. Yes, I have added yet another method to my class, but it's easier to read in the long run in my humble opinion.
You may use
to automatically generate the builder with default values.
Just add @GenerateMethodInvocationBuilder to the class, or interface, and the @Default to parameters in methods where you want default values. A builder will be generated at compile time, using the default values that you specified with your annotations.
@GenerateMethodInvocationBuilder
public class CarService {
public CarService() {
public String getCarsByFilter(//
@Default("Color.BLUE") Color color, //
@Default("new ProductionYear(2001)") ProductionYear productionYear,//
@Default("Tomas") String owner//
return "Filtering... " + color + productionYear +
And then you can invoke the methods.
CarService instance = new CarService();
String carsByFilter = CarServiceGetCarsByFilterBuilder.getCarsByFilter()//
.invoke(instance);
Or set any of the default values to something else.
CarService instance = new CarService();
String carsByFilter = CarServiceGetCarsByFilterBuilder.getCarsByFilter()//
.withColor(Color.YELLOW)//
.invoke(instance);
No, but the simplest way to implement this is:
public MyParameterizedFunction(String param1, int param2, Boolean param3) {
param3 = param3 == null ? false : param3;
public MyParameterizedFunction(String param1, int param2) {
this(param1, param2, false);
Or instead of the ternary operator you can use if:
public MyParameterizedFunction(String param1, int param2, Boolean param3) {
if (param3 == null) {
public MyParameterizedFunction(String param1, int param2) {
this(param1, param2, false);
2,44621828
protected by ♦
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10
on this site (the ).
Would you like to answer one of these
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled

我要回帖

更多关于 init param 的文章

 

随机推荐