简体   繁体   English

Java 发送可选参数

[英]Java Send Optional Parameters

I have a decision in my Java application.我的 Java 申请中有一个决定。

if (variable == 0) {
   // call a function without parameter 
   func();
} else {
   // call a function with parameter 
   func(variable);
}

Could I do this call (function) with or without parameter in just one line?我可以在一行中使用或不使用参数来执行此调用(函数)吗? This problem is because the function can't receive "Zero", just a valid ID.这个问题是因为 function 不能接收“零”,只是一个有效的 ID。

What I want to do is somenthing like that.我想做的就是这样。 (ternary operation) Here is the main problem what I want to resolve (三元运算)这是我要解决的主要问题

 //condition ? truth : false; to allow to send with or without parameter 
 func( (variable!=0?Id:null) )

And then the Java will decision what function access.然后 Java 将决定 function 访问什么。

I declared my function like below in my repository我在我的存储库中声明了我的 function 如下所示

    @Query("select c from Cliente c "
            + " where c.id = :id "
            + " and  c.negativar = true" )
    List<Cliente> findClients(@Param("id") Integer id);

    @Query("select c from Cliente c "
            + " where  "
            + "   c.negativar = true" )
    List<Cliente> findClients();


No.不。

In java, a method's identity is not just the name.在 java 中,方法的标识不仅仅是名称。 It's 3 things: The type it appears in, the name, and the parameter types.这是三件事:它出现的类型、名称和参数类型。 Parameter names don't matter, but types do.参数名称无关紧要,但类型很重要。

In other words:换句话说:

void foo() {}
void foo(int i) {}

are 2 methods that have no relationship of any sort.是两种没有任何关系的方法。 They are exactly as different as:它们完全不同:

void foo() {}
void bar() {}

are.是。 Thus, there is no mechanism in the language to invoke either foo() or foo(someInt) depending on the state of a value, and there never will be, because it fundamentally doesn't make sense given how java works.因此,语言中没有机制可以根据值的 state 调用foo()foo(someInt) ,而且永远不会有,因为考虑到 java 的工作方式,它从根本上说没有意义。

The usual solution is either builders, which seems like completely overkill here, or sentinel values.通常的解决方案是建造者,这在这里看起来完全是矫枉过正,或者哨兵价值观。

sentinel values might make sense here: the func definition should presumably treat func(0);哨兵值在这里可能有意义: func定义大概应该处理func(0); as the same as func() , but apparently it doesn't, in which case, the if/else block you have is as good as it's ever going to get.func()相同,但显然不是,在这种情况下,您拥有的 if/else 块将与以往一样好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM