如何使用 lambda 表达式将条件发送到方法以便尚未对其进行评估?
How to send a condition to a method using lambda expression so that it is not yet evaluated?
我正在尝试将条件语句(尚未评估)作为参数发送给方法。我知道在 java8 中,lambda 表达式 是实现它的方法(有效地将条件放入函数中,并发送函数)。
// simple method inside a utilities class
// that does assertions if global debug parameter is true
public class MyUtils
{
public static void do_assertions( boolean argb , String args )
{
if( BuildConfig.pvb_debuggable )
{ assert argb , args ;
}
}
}
// somewhere within app where a development-phase assertion is needed
public class some_class
{
public void some_method( )
{
EditText lvo_editText = (EditText) findViewById( "the_id" ) ;
//assert lvo_editText != null;
// ... replace this with a call to do_assertions
MyUtils.do_assertions( () -> { lvo_editText != null ; } , "bad EditText" );
}
}
我已经尝试过此设置的多种变体。我每次都会收到不同的错误 :)
您快到了,您可以更改您的签名以接收一个 BooleanSupplier,它将仅在调用 getAsBoolean
.
时评估条件
这里有一个简单的例子:
public class Test {
public static void main(String args[]) {
A a = new A();
test(() -> a != null && a.get());
}
static void test(BooleanSupplier condition) {
condition.getAsBoolean();
}
static class A {
boolean get(){
return true;
}
}
}
如果您在调试模式下查看此示例,您会看到仅在执行 condition.getAsBoolean()
时才评估条件 a != null && a.get()
。
将此应用于您的示例,您只需更改
void do_assertions( boolean argb , String args )
为
void do_assertions(BooleanSupplier argo_supplier , String args )
然后调用 argo_supplier.getAsBoolean()
你想评估条件的地方(检查 pvb_debuggable
之后)。
然后你的台词
MyUtils.do_assertions( () -> lvo_editText != null , "bad EditText" );
会正确编译(注意我删除了不必要的括号)。
我正在尝试将条件语句(尚未评估)作为参数发送给方法。我知道在 java8 中,lambda 表达式 是实现它的方法(有效地将条件放入函数中,并发送函数)。
// simple method inside a utilities class
// that does assertions if global debug parameter is true
public class MyUtils
{
public static void do_assertions( boolean argb , String args )
{
if( BuildConfig.pvb_debuggable )
{ assert argb , args ;
}
}
}
// somewhere within app where a development-phase assertion is needed
public class some_class
{
public void some_method( )
{
EditText lvo_editText = (EditText) findViewById( "the_id" ) ;
//assert lvo_editText != null;
// ... replace this with a call to do_assertions
MyUtils.do_assertions( () -> { lvo_editText != null ; } , "bad EditText" );
}
}
我已经尝试过此设置的多种变体。我每次都会收到不同的错误 :)
您快到了,您可以更改您的签名以接收一个 BooleanSupplier,它将仅在调用 getAsBoolean
.
这里有一个简单的例子:
public class Test {
public static void main(String args[]) {
A a = new A();
test(() -> a != null && a.get());
}
static void test(BooleanSupplier condition) {
condition.getAsBoolean();
}
static class A {
boolean get(){
return true;
}
}
}
如果您在调试模式下查看此示例,您会看到仅在执行 condition.getAsBoolean()
时才评估条件 a != null && a.get()
。
将此应用于您的示例,您只需更改
void do_assertions( boolean argb , String args )
为
void do_assertions(BooleanSupplier argo_supplier , String args )
然后调用 argo_supplier.getAsBoolean()
你想评估条件的地方(检查 pvb_debuggable
之后)。
然后你的台词
MyUtils.do_assertions( () -> lvo_editText != null , "bad EditText" );
会正确编译(注意我删除了不必要的括号)。