Created
December 4, 2014 12:14
-
-
Save vshank77/c799f8952414e912b291 to your computer and use it in GitHub Desktop.
Stupid Compiler Optimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package serpentes.testing; | |
import org.testng.annotations.Test; | |
import java.lang.reflect.Field; | |
import static org.testng.Assert.assertEquals; | |
public class FunClassTest { | |
@Test | |
public void explainThis() { | |
FunClass fun = new FunClass("value"); | |
assertEquals("value", fun.changeable()); | |
assertEquals("", fun.unchangeable()); | |
fun.changeable("newC"); | |
fun.unchangeable("newU"); | |
assertEquals("newC", fun.changeable()); | |
assertEquals("newU", fun.reflectGet("unchangeable")); | |
//??WHY THE FOLLOWING | |
assertEquals("", fun.unchangeable()); | |
} | |
private static class FunClass { | |
private final String changeable; | |
private final String unchangeable = ""; | |
public FunClass(String str) { | |
this.changeable = str; | |
} | |
public String changeable() { | |
return changeable; | |
} | |
public String unchangeable() { | |
return unchangeable; | |
} | |
public void changeable(String newVal) { | |
reflectSet("changeable", newVal); | |
} | |
public void unchangeable(String newVal) { | |
reflectSet("unchangeable", newVal); | |
} | |
@SuppressWarnings("unchecked") | |
public <T> T reflectGet(String name) { | |
try { | |
Field field = getClass().getDeclaredField(name); | |
field.setAccessible(true); | |
return (T) field.get(this); | |
} catch (Exception e) { | |
throw new IllegalStateException("unable to set field value", e); | |
} | |
} | |
private void reflectSet(String name, Object value) { | |
try { | |
Field field = getClass().getDeclaredField(name); | |
field.setAccessible(true); | |
field.set(this, value); | |
} catch (Exception e) { | |
throw new IllegalStateException("unable to set field value", e); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment