在下面的给定代码中,我的行为模棱两可:
public class Main {
public static void main(String[] args) {
labo(Main::myFunction);
labo(Main::myFunctionWithNoArgs);//Compiletime exception!!!
labo(String::toUpperCase);//Compiled line!!!
}
public static void labo(Function<String,String> function){
System.out.println(function.apply("test"));
}
public static String myFunction(String arg){
return arg;
}
public static String myFunctionWithNoArgs(){
return "";
}
}
我的问题是:我不明白为什么我没有得到arg String :: toUpperCase的编译时异常,而Main :: myFunctionWithNoArgs却没有,即使toUpperCase()是与myFunctionWithNoArgs()一样没有args的方法。 / p>
答案 0 :(得分:2)
protected void fireActionPerformed(ActionEvent e)
{
// Dispatch a copy of the given ActionEvent in order to
// set the source and action command correctly.
ActionEvent ae = new ActionEvent(
this,
e.getID(),
getActionCommand(),
e.getWhen(),
e.getModifiers());
ActionListener[] listeners = getActionListeners();
for (int i = 0; i < listeners.length; i++) //no way to prematurely terminate this loop
listeners[i].actionPerformed(ae);
}
等效于String::toUpperCase
,即它是从s -> s.toUpperCase()
到String
的函数。
此处的“参数”是方法的接收者,即String
下注转换为大写。
答案 1 :(得分:1)
如果将其写为lambda可能更有意义:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="priority-lists">
<div class="accordian">
<div class="accordian-item">
<div class="accordian-title">TITLE<span class="accordian-title-icon"></span></div>
<div class="accordian-content" style="display: none;">
<p>This is a sentence.</p>
</div>
</div>
<div class="accordian-item">
<div class="accordian-title">TITLE<span class="accordian-title-icon"></span></div>
<div class="accordian-content" style="display: none;">
<p>This is a sentence</p>
</div>
</div>
<div class="accordian-item">
<div class="accordian-title">TITLE<span class="accordian-title-icon"></span></div>
<div class="accordian-content" style="display: none;">
<p>this is a sentence</p>
</div>
</div>
</div>
<h2>SECTION 2</h2>
<div class="priority-lists">
<div class="accordian">
<div class="accordian-item">
<div class="accordian-title">TITLE<span class="accordian-title-icon"></span></div>
<div class="accordian-content" style="display: none;">
<p>This is a sentence.</p>
</div>
</div>
<div class="accordian-item">
<div class="accordian-title">TITLE<span class="accordian-title-icon"></span></div>
<div class="accordian-content" style="display: none;">
<p>This is a sentence</p>
</div>
</div>
<div class="accordian-item">
<div class="accordian-title">TITLE<span class="accordian-title-icon"></span></div>
<div class="accordian-content" style="display: none;">
<p>this is a sentence</p>
</div>
</div>
</div>