Can (a==1 && a==2 && a==3) evaluate to true in Java?

后端 未结 8 743
梦如初夏
梦如初夏 2020-11-29 15:01

We know it can in JavaScript.

But is it possible to print \"Success\" message on the condition given below in Java?

if (a==1 && a==2 &&am         


        
8条回答
  •  心在旅途
    2020-11-29 15:37

    There is another way to approach this (in additional to the volatile data-racing approach that I posted earlier), using the power of PowerMock. PowerMock allows methods to be replaced with other implementations. When that is combined with auto-unboxing, the original expression (a == 1 && a == 2 && a == 3), without modification, can be made true.

    @phflack's answer relies on modifying the auto-boxing process in Java that uses the Integer.valueOf(...) call. The below approach relies on modifying auto-unboxing by changed the Integer.intValue() call.

    The advantage of the below approach is that the original if-statement given by the OP in the question is used unchanged, which I think is the most elegant.

    import static org.powermock.api.support.membermodification.MemberMatcher.method;
    import static org.powermock.api.support.membermodification.MemberModifier.replace;
    
    import java.util.concurrent.atomic.AtomicInteger;
    
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @PrepareForTest(Integer.class)
    @RunWith(PowerMockRunner.class)
    public class Ais123 {
        @Before
        public void before() {
            // "value" is just a place to store an incrementing integer
            AtomicInteger value = new AtomicInteger(1);
            replace(method(Integer.class, "intValue"))
                .with((proxy, method, args) -> value.getAndIncrement());
        }
    
        @Test
        public void test() {
            Integer a = 1;
    
            if (a == 1 && a == 2 && a == 3) {
                System.out.println("Success");
            } else {
                Assert.fail("(a == 1 && a == 2 && a == 3) != true, a = " + a.intValue());
            }
        }
    
    }
    

提交回复
热议问题