Related
I have a class with a hasField function that checks if a field is present and not null, and a getField function that returns the value of the field (or null if not present).
In my code when I call getField right after checking hasField, I know that getField is not going to return null, but the IDE Inspection (Constant Conditions and Exceptions) doesn't know that. I get a bunch of method method name may produce a NullPointerException
I'm trying to find a clean way to make this warning go away.
Workarounds
Here are some workarounds I could do but I find all of these hacky:
Surround getField with Objects.requireNotnull, the code would be no-op. Would prefer not doing that as it makes the code slightly less readable.
Suppress warnings where I know this is safe. Again not preferred as this is going to happen at a bunch of places in our code.
Ignore warnings. In this case we might miss legit warnings just because warnings section will be too noisy.
Ideal solution
Would I be able to somehow set up the warnings in such a way that if hasField is true, then getField will return a non-null? I looked into JetBrains Contract Annotations but doing what I want here seems to be beyond what is supported with #Contract
Code Sample
Here's a minimum working code sample that demonstrates the issue:
import javax.annotation.Nullable;
public class Hello {
private Hello(){}
public static void main(String[] args) {
TestClass test1 = new TestClass(null);
if (test1.hasSample()) {
System.out.println(test1.getSample().equals("abc"));
}
}
}
class TestClass {
private final String sample;
TestClass(String field) { this.sample = field; }
boolean hasSample() { return sample != null; }
#Nullable public String getSample() { return sample; }
}
I get the following warning
Method invocation equals may produce NullPointerException
I'd ideally want to be able to tell IDE that getSample is not null when hasSample is true.
Disclosure I'm IntelliJ IDEA developer responsible for this subsystem
No, it's not possible now. There's no better solution than possible workarounds you already listed, assuming that you cannot change the API. The closest thing we have is the inlining of very trivial methods. However, it works only if:
The methods like hasSample() and getSample() are called from the same class
The called methods cannot be overridden (private/static/final/declared in final class)
E.g. this feature works in the following code:
final class TestClass { // if final is removed, the warning will appear again
private final String sample;
TestClass(String field) { this.sample = field; }
boolean hasSample() { return sample != null; }
#Nullable
public String getSample() { return sample; }
#Override
public String toString() {
if (hasSample()) {
return "TestClass: "+getSample().trim(); // no warning on trim() invocation here
}
return "TestClass";
}
}
For now, I can only suggest refactoring your APIs to Optionals like this:
import java.util.Optional;
public class Hello {
private Hello(){}
public static void main(String[] args) {
TestClass test1 = new TestClass(null);
test1.getSample().ifPresent(s -> System.out.println(s.equals("abc")));
// or fancier: test1.getSample().map("abc"::equals).ifPresent(System.out::println);
}
}
final class TestClass {
private final String sample;
TestClass(String field) { this.sample = field; }
public Optional<String> getSample() { return Optional.ofNullable(sample); }
}
Please have a look at the following code:
Method methodInfo = MyClass.class.getMethod("myMethod");
This works, but the method name is passed as a string, so this will compile even if myMethod does not exist.
On the other hand, Java 8 introduces a method reference feature. It is checked at compile time. It is possible to use this feature to get method info?
printMethodName(MyClass::myMethod);
Full example:
#FunctionalInterface
private interface Action {
void invoke();
}
private static class MyClass {
public static void myMethod() {
}
}
private static void printMethodName(Action action) {
}
public static void main(String[] args) throws NoSuchMethodException {
// This works, but method name is passed as a string, so this will compile
// even if myMethod does not exist
Method methodInfo = MyClass.class.getMethod("myMethod");
// Here we pass reference to a method. It is somehow possible to
// obtain java.lang.reflect.Method for myMethod inside printMethodName?
printMethodName(MyClass::myMethod);
}
In other words I would like to have a code which is the equivalent of the following C# code:
private static class InnerClass
{
public static void MyMethod()
{
Console.WriteLine("Hello");
}
}
static void PrintMethodName(Action action)
{
// Can I get java.lang.reflect.Method in the same way?
MethodInfo methodInfo = action.GetMethodInfo();
}
static void Main()
{
PrintMethodName(InnerClass.MyMethod);
}
No, there is no reliable, supported way to do this. You assign a method reference to an instance of a functional interface, but that instance is cooked up by LambdaMetaFactory, and there is no way to drill into it to find the method you originally bound to.
Lambdas and method references in Java work quite differently than delegates in C#. For some interesting background, read up on invokedynamic.
Other answers and comments here show that it may currently be possible to retrieve the bound method with some additional work, but make sure you understand the caveats.
In my case I was looking for a way to get rid of this in unit tests:
Point p = getAPoint();
assertEquals(p.getX(), 4, "x");
assertEquals(p.getY(), 6, "x");
As you can see someone is testing Method getAPoint and checks that the coordinates are as expected, but in the description of each assert was copied and is not in sync with what is checked. Better would be to write this only once.
From the ideas by #ddan I built a proxy solution using Mockito:
private<T> void assertPropertyEqual(final T object, final Function<T, ?> getter, final Object expected) {
final String methodName = getMethodName(object.getClass(), getter);
assertEquals(getter.apply(object), expected, methodName);
}
#SuppressWarnings("unchecked")
private<T> String getMethodName(final Class<?> clazz, final Function<T, ?> getter) {
final Method[] method = new Method[1];
getter.apply((T)Mockito.mock(clazz, Mockito.withSettings().invocationListeners(methodInvocationReport -> {
method[0] = ((InvocationOnMock) methodInvocationReport.getInvocation()).getMethod();
})));
return method[0].getName();
}
No I can simply use
assertPropertyEqual(p, Point::getX, 4);
assertPropertyEqual(p, Point::getY, 6);
and the description of the assert is guaranteed to be in sync with the code.
Downside:
Will be slightly slower than above
Needs Mockito to work
Hardly useful to anything but the usecase above.
However it does show a way how it could be done.
Though I haven't tried it myself, I think the answer is "no," since a method reference is semantically the same as a lambda.
You can add safety-mirror to your classpath and do like this:
Method m1 = Types.createMethod(Thread::isAlive) // Get final method
Method m2 = Types.createMethod(String::isEmpty); // Get method from final class
Method m3 = Types.createMethod(BufferedReader::readLine); // Get method that throws checked exception
Method m4 = Types.<String, Class[]>createMethod(getClass()::getDeclaredMethod); //to get vararg method you must specify parameters in generics
Method m5 = Types.<String>createMethod(Class::forName); // to get overloaded method you must specify parameters in generics
Method m6 = Types.createMethod(this::toString); //Works with inherited methods
The library also offers a getName(...) method:
assertEquals("isEmpty", Types.getName(String::isEmpty));
The library is based on Holger's answer: https://stackoverflow.com/a/21879031/6095334
Edit: The library have various shortcomings which I am slowly becoming aware of.
See fx Holger's comment here: How to get the name of the method resulting from a lambda
There may not be a reliable way, but under some circumstances:
your MyClass is not final, and has an accessible constructor (limitation of cglib)
your myMethod is not overloaded, and not static
The you can try using cglib to create a proxy of MyClass, then using an MethodInterceptor to report the Method while the method reference is invoked in a following trial run.
Example code:
public static void main(String[] args) {
Method m = MethodReferenceUtils.getReferencedMethod(ArrayList.class, ArrayList::contains);
System.out.println(m);
}
You will see the following output:
public boolean java.util.ArrayList.contains(java.lang.Object)
While:
public class MethodReferenceUtils {
#FunctionalInterface
public static interface MethodRefWith1Arg<T, A1> {
void call(T t, A1 a1);
}
public static <T, A1> Method getReferencedMethod(Class<T> clazz, MethodRefWith1Arg<T, A1> methodRef) {
return findReferencedMethod(clazz, t -> methodRef.call(t, null));
}
#SuppressWarnings("unchecked")
private static <T> Method findReferencedMethod(Class<T> clazz, Consumer<T> invoker) {
AtomicReference<Method> ref = new AtomicReference<>();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(new MethodInterceptor() {
#Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
ref.set(method);
return null;
}
});
try {
invoker.accept((T) enhancer.create());
} catch (ClassCastException e) {
throw new IllegalArgumentException(String.format("Invalid method reference on class [%s]", clazz));
}
Method method = ref.get();
if (method == null) {
throw new IllegalArgumentException(String.format("Invalid method reference on class [%s]", clazz));
}
return method;
}
}
In the above code, MethodRefWith1Arg is just a syntax sugar for you to reference an non-static method with one arguments. You can create as many as MethodRefWithXArgs for referencing your other methods.
If you can make the interface Action extend Serializable, then this answer from another question seems to provide a solution (at least on some compilers and runtimes).
We have published the small library reflection-util that can be used to capture a method name.
Example:
class MyClass {
private int value;
public void myMethod() {
}
public int getValue() {
return value;
}
}
String methodName = ClassUtils.getMethodName(MyClass.class, MyClass::myMethod);
System.out.println(methodName); // prints "myMethod"
String getterName = ClassUtils.getMethodName(MyClass.class, MyClass::getValue);
System.out.println(getterName); // prints "getValue"
Implementation details: A Proxy subclass of MyClass is created with ByteBuddy and a call to the method is captured to retrieve its name.
ClassUtils caches the information such that we do not need to create a new proxy on every invocation.
Please note that this approach is no silver bullet and there are some known cases that don’t work:
It doesn’t work for static methods.
It doesn’t work if the class is final.
We currently do not support all potential method signatures. It should work for methods that do not take an argument such as a getter method.
You can use my library Reflect Without String
Method myMethod = ReflectWithoutString.methodGetter(MyClass.class).getMethod(MyClass::myMethod);
Another solution using Mockito:
pom.xml:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>compile</scope>
</dependency>
Test code:
public class MethodUtilTest {
#Test
void testMethodNameGetter() {
final Method method = MethodUtil.getMethodFromGetter(DummyClass.class, DummyClass::getTestString);
Assertions.assertEquals("getTestString", method.getName());
}
#Test
void testMethodNameSetter() {
final Method method = MethodUtil.getMethodFromSetter(DummyClass.class, DummyClass::setTestString);
Assertions.assertEquals("setTestString", method.getName());
}
}
java code:
public class MethodUtil {
public static <T> Method getMethodFromGetter(final Class<T> clazz, final Function<T, ?> getter) {
return captureMethodOnInvocation(clazz, getter::apply);
}
public static <T, V> Method getMethodFromSetter(final Class<T> clazz, final BiConsumer<T, V> setter) {
return captureMethodOnInvocation(clazz, (T mock) -> setter.accept(mock, ArgumentMatchers.any()));
}
private static <T> Method captureMethodOnInvocation(final Class<T> clazz, final Consumer<T> invokeMock) {
try {
final AtomicReference<Method> methodReference = new AtomicReference<>();
final InvocationListener invocationListener = new InvocationListener() {
#Override
public void reportInvocation(final MethodInvocationReport methodInvocationReport) {
final Method method = ((InvocationOnMock) methodInvocationReport.getInvocation()).getMethod();
methodReference.set(method);
}
};
final MockSettings mockSettings = Mockito.withSettings().invocationListeners(invocationListener);
final T mock = Mockito.mock(clazz, mockSettings);
invokeMock.accept(mock);
return methodReference.get();
} catch (final Exception e) {
throw new RuntimeException("Method could not be captured at runtime.", e);
}
}
}
So, I play with this code
import sun.reflect.ConstantPool;
import java.lang.reflect.Method;
import java.util.function.Consumer;
public class Main {
private Consumer<String> consumer;
Main() {
consumer = this::test;
}
public void test(String val) {
System.out.println("val = " + val);
}
public void run() throws Exception {
ConstantPool oa = sun.misc.SharedSecrets.getJavaLangAccess().getConstantPool(consumer.getClass());
for (int i = 0; i < oa.getSize(); i++) {
try {
Object v = oa.getMethodAt(i);
if (v instanceof Method) {
System.out.println("index = " + i + ", method = " + v);
}
} catch (Exception e) {
}
}
}
public static void main(String[] args) throws Exception {
new Main().run();
}
}
output of this code is:
index = 30, method = public void Main.test(java.lang.String)
And as I notice index of referenced method is always 30.
Final code may look like
public Method unreference(Object methodRef) {
ConstantPool constantPool = sun.misc.SharedSecrets.getJavaLangAccess().getConstantPool(methodRef.getClass());
try {
Object method = constantPool.getMethodAt(30);
if (method instanceof Method) {
return (Method) method;
}
}catch (Exception ignored) {
}
throw new IllegalArgumentException("Not a method reference.");
}
Be careful with this code in production!
Try this
Thread.currentThread().getStackTrace()[2].getMethodName();
Please have a look at the following code:
Method methodInfo = MyClass.class.getMethod("myMethod");
This works, but the method name is passed as a string, so this will compile even if myMethod does not exist.
On the other hand, Java 8 introduces a method reference feature. It is checked at compile time. It is possible to use this feature to get method info?
printMethodName(MyClass::myMethod);
Full example:
#FunctionalInterface
private interface Action {
void invoke();
}
private static class MyClass {
public static void myMethod() {
}
}
private static void printMethodName(Action action) {
}
public static void main(String[] args) throws NoSuchMethodException {
// This works, but method name is passed as a string, so this will compile
// even if myMethod does not exist
Method methodInfo = MyClass.class.getMethod("myMethod");
// Here we pass reference to a method. It is somehow possible to
// obtain java.lang.reflect.Method for myMethod inside printMethodName?
printMethodName(MyClass::myMethod);
}
In other words I would like to have a code which is the equivalent of the following C# code:
private static class InnerClass
{
public static void MyMethod()
{
Console.WriteLine("Hello");
}
}
static void PrintMethodName(Action action)
{
// Can I get java.lang.reflect.Method in the same way?
MethodInfo methodInfo = action.GetMethodInfo();
}
static void Main()
{
PrintMethodName(InnerClass.MyMethod);
}
No, there is no reliable, supported way to do this. You assign a method reference to an instance of a functional interface, but that instance is cooked up by LambdaMetaFactory, and there is no way to drill into it to find the method you originally bound to.
Lambdas and method references in Java work quite differently than delegates in C#. For some interesting background, read up on invokedynamic.
Other answers and comments here show that it may currently be possible to retrieve the bound method with some additional work, but make sure you understand the caveats.
In my case I was looking for a way to get rid of this in unit tests:
Point p = getAPoint();
assertEquals(p.getX(), 4, "x");
assertEquals(p.getY(), 6, "x");
As you can see someone is testing Method getAPoint and checks that the coordinates are as expected, but in the description of each assert was copied and is not in sync with what is checked. Better would be to write this only once.
From the ideas by #ddan I built a proxy solution using Mockito:
private<T> void assertPropertyEqual(final T object, final Function<T, ?> getter, final Object expected) {
final String methodName = getMethodName(object.getClass(), getter);
assertEquals(getter.apply(object), expected, methodName);
}
#SuppressWarnings("unchecked")
private<T> String getMethodName(final Class<?> clazz, final Function<T, ?> getter) {
final Method[] method = new Method[1];
getter.apply((T)Mockito.mock(clazz, Mockito.withSettings().invocationListeners(methodInvocationReport -> {
method[0] = ((InvocationOnMock) methodInvocationReport.getInvocation()).getMethod();
})));
return method[0].getName();
}
No I can simply use
assertPropertyEqual(p, Point::getX, 4);
assertPropertyEqual(p, Point::getY, 6);
and the description of the assert is guaranteed to be in sync with the code.
Downside:
Will be slightly slower than above
Needs Mockito to work
Hardly useful to anything but the usecase above.
However it does show a way how it could be done.
Though I haven't tried it myself, I think the answer is "no," since a method reference is semantically the same as a lambda.
You can add safety-mirror to your classpath and do like this:
Method m1 = Types.createMethod(Thread::isAlive) // Get final method
Method m2 = Types.createMethod(String::isEmpty); // Get method from final class
Method m3 = Types.createMethod(BufferedReader::readLine); // Get method that throws checked exception
Method m4 = Types.<String, Class[]>createMethod(getClass()::getDeclaredMethod); //to get vararg method you must specify parameters in generics
Method m5 = Types.<String>createMethod(Class::forName); // to get overloaded method you must specify parameters in generics
Method m6 = Types.createMethod(this::toString); //Works with inherited methods
The library also offers a getName(...) method:
assertEquals("isEmpty", Types.getName(String::isEmpty));
The library is based on Holger's answer: https://stackoverflow.com/a/21879031/6095334
Edit: The library have various shortcomings which I am slowly becoming aware of.
See fx Holger's comment here: How to get the name of the method resulting from a lambda
There may not be a reliable way, but under some circumstances:
your MyClass is not final, and has an accessible constructor (limitation of cglib)
your myMethod is not overloaded, and not static
The you can try using cglib to create a proxy of MyClass, then using an MethodInterceptor to report the Method while the method reference is invoked in a following trial run.
Example code:
public static void main(String[] args) {
Method m = MethodReferenceUtils.getReferencedMethod(ArrayList.class, ArrayList::contains);
System.out.println(m);
}
You will see the following output:
public boolean java.util.ArrayList.contains(java.lang.Object)
While:
public class MethodReferenceUtils {
#FunctionalInterface
public static interface MethodRefWith1Arg<T, A1> {
void call(T t, A1 a1);
}
public static <T, A1> Method getReferencedMethod(Class<T> clazz, MethodRefWith1Arg<T, A1> methodRef) {
return findReferencedMethod(clazz, t -> methodRef.call(t, null));
}
#SuppressWarnings("unchecked")
private static <T> Method findReferencedMethod(Class<T> clazz, Consumer<T> invoker) {
AtomicReference<Method> ref = new AtomicReference<>();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(new MethodInterceptor() {
#Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
ref.set(method);
return null;
}
});
try {
invoker.accept((T) enhancer.create());
} catch (ClassCastException e) {
throw new IllegalArgumentException(String.format("Invalid method reference on class [%s]", clazz));
}
Method method = ref.get();
if (method == null) {
throw new IllegalArgumentException(String.format("Invalid method reference on class [%s]", clazz));
}
return method;
}
}
In the above code, MethodRefWith1Arg is just a syntax sugar for you to reference an non-static method with one arguments. You can create as many as MethodRefWithXArgs for referencing your other methods.
If you can make the interface Action extend Serializable, then this answer from another question seems to provide a solution (at least on some compilers and runtimes).
We have published the small library reflection-util that can be used to capture a method name.
Example:
class MyClass {
private int value;
public void myMethod() {
}
public int getValue() {
return value;
}
}
String methodName = ClassUtils.getMethodName(MyClass.class, MyClass::myMethod);
System.out.println(methodName); // prints "myMethod"
String getterName = ClassUtils.getMethodName(MyClass.class, MyClass::getValue);
System.out.println(getterName); // prints "getValue"
Implementation details: A Proxy subclass of MyClass is created with ByteBuddy and a call to the method is captured to retrieve its name.
ClassUtils caches the information such that we do not need to create a new proxy on every invocation.
Please note that this approach is no silver bullet and there are some known cases that don’t work:
It doesn’t work for static methods.
It doesn’t work if the class is final.
We currently do not support all potential method signatures. It should work for methods that do not take an argument such as a getter method.
You can use my library Reflect Without String
Method myMethod = ReflectWithoutString.methodGetter(MyClass.class).getMethod(MyClass::myMethod);
Another solution using Mockito:
pom.xml:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>compile</scope>
</dependency>
Test code:
public class MethodUtilTest {
#Test
void testMethodNameGetter() {
final Method method = MethodUtil.getMethodFromGetter(DummyClass.class, DummyClass::getTestString);
Assertions.assertEquals("getTestString", method.getName());
}
#Test
void testMethodNameSetter() {
final Method method = MethodUtil.getMethodFromSetter(DummyClass.class, DummyClass::setTestString);
Assertions.assertEquals("setTestString", method.getName());
}
}
java code:
public class MethodUtil {
public static <T> Method getMethodFromGetter(final Class<T> clazz, final Function<T, ?> getter) {
return captureMethodOnInvocation(clazz, getter::apply);
}
public static <T, V> Method getMethodFromSetter(final Class<T> clazz, final BiConsumer<T, V> setter) {
return captureMethodOnInvocation(clazz, (T mock) -> setter.accept(mock, ArgumentMatchers.any()));
}
private static <T> Method captureMethodOnInvocation(final Class<T> clazz, final Consumer<T> invokeMock) {
try {
final AtomicReference<Method> methodReference = new AtomicReference<>();
final InvocationListener invocationListener = new InvocationListener() {
#Override
public void reportInvocation(final MethodInvocationReport methodInvocationReport) {
final Method method = ((InvocationOnMock) methodInvocationReport.getInvocation()).getMethod();
methodReference.set(method);
}
};
final MockSettings mockSettings = Mockito.withSettings().invocationListeners(invocationListener);
final T mock = Mockito.mock(clazz, mockSettings);
invokeMock.accept(mock);
return methodReference.get();
} catch (final Exception e) {
throw new RuntimeException("Method could not be captured at runtime.", e);
}
}
}
So, I play with this code
import sun.reflect.ConstantPool;
import java.lang.reflect.Method;
import java.util.function.Consumer;
public class Main {
private Consumer<String> consumer;
Main() {
consumer = this::test;
}
public void test(String val) {
System.out.println("val = " + val);
}
public void run() throws Exception {
ConstantPool oa = sun.misc.SharedSecrets.getJavaLangAccess().getConstantPool(consumer.getClass());
for (int i = 0; i < oa.getSize(); i++) {
try {
Object v = oa.getMethodAt(i);
if (v instanceof Method) {
System.out.println("index = " + i + ", method = " + v);
}
} catch (Exception e) {
}
}
}
public static void main(String[] args) throws Exception {
new Main().run();
}
}
output of this code is:
index = 30, method = public void Main.test(java.lang.String)
And as I notice index of referenced method is always 30.
Final code may look like
public Method unreference(Object methodRef) {
ConstantPool constantPool = sun.misc.SharedSecrets.getJavaLangAccess().getConstantPool(methodRef.getClass());
try {
Object method = constantPool.getMethodAt(30);
if (method instanceof Method) {
return (Method) method;
}
}catch (Exception ignored) {
}
throw new IllegalArgumentException("Not a method reference.");
}
Be careful with this code in production!
Try this
Thread.currentThread().getStackTrace()[2].getMethodName();
I am trying to write a unit test for a legacy code. The class which I'm testing has several static variables. My test case class has a few #Test methods. Hence all of them share the same state.
Is there way to reset all static variables between tests?
One solution I came up is to explicitly reset each field, e.g.:
field(MyUnit.class, "staticString").set(null, null);
((Map) field(MyUnit.class, "staticFinalHashMap").get(null)).clear();
As you see, each variable needs custom re-initialization. The approach is not easy to scale, there are a lot such classes in the legacy code base. Is there any way to reset everything at once? Maybe by reloading the class each time?
As a possible good solution I think is to use something like powermock and create a separate classloader for each test. But I don't see easy way to do it.
Ok, I think I figured it out. It is very simple.
It is possible to move #PrepareForTest powermock's annotation to the method level. In this case powermock creates classloader per method. So it does that I need.
Let's say I'm testing some code involving this class:
import java.math.BigInteger;
import java.util.HashSet;
public class MyClass {
static int someStaticField = 5;
static BigInteger anotherStaticField = BigInteger.ONE;
static HashSet<Integer> mutableStaticField = new HashSet<Integer>();
}
You can reset all of the static fields programmatically using Java's reflection capabilities. You will need to store all of the initial values before you begin the test, and then you'll need to reset those values before each test is run. JUnit has #BeforeClass and #Before annotations that work nicely for this. Here's a simple example:
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.util.Map;
import java.util.HashMap;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class MyTest extends Object {
static Class<?> staticClass = MyClass.class;
static Map<Field,Object> defaultFieldVals = new HashMap<Field,Object>();
static Object tryClone(Object v) throws Exception {
if (v instanceof Cloneable) {
return v.getClass().getMethod("clone").invoke(v);
}
return v;
}
#BeforeClass
public static void setUpBeforeClass() throws Exception {
Field[] allFields = staticClass.getDeclaredFields();
try {
for (Field field : allFields) {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
Object value = tryClone(field.get(null));
defaultFieldVals.put(field, value);
}
}
}
catch (IllegalAccessException e) {
System.err.println(e);
System.exit(1);
}
}
#AfterClass
public static void tearDownAfterClass() {
defaultFieldVals = null;
}
#Before
public void setUp() throws Exception {
// Reset all static fields
for (Map.Entry<Field, Object> entry : defaultFieldVals.entrySet()) {
Field field = entry.getKey();
Object value = entry.getValue();
Class<?> type = field.getType();
// Primitive types
if (type == Integer.TYPE) {
field.setInt(null, (Integer) value);
}
// ... all other primitive types need to be handled similarly
// All object types
else {
field.set(null, tryClone(value));
}
}
}
private void testBody() {
assertTrue(MyClass.someStaticField == 5);
assertTrue(MyClass.anotherStaticField == BigInteger.ONE);
assertTrue(MyClass.mutableStaticField.isEmpty());
MyClass.someStaticField++;
MyClass.anotherStaticField = BigInteger.TEN;
MyClass.mutableStaticField.add(1);
assertTrue(MyClass.someStaticField == 6);
assertTrue(MyClass.anotherStaticField.equals(BigInteger.TEN));
assertTrue(MyClass.mutableStaticField.contains(1));
}
#Test
public void test1() {
testBody();
}
#Test
public void test2() {
testBody();
}
}
As I noted in the comments in setUp(), you'll need to handle the rest of the primitive types with similar code for that to handle ints. All of the wrapper classes have a TYPE field (e.g. Double.TYPE and Character.TYPE) which you can check just like Integer.TYPE. If the field's type isn't one of the primitive types (including primitive arrays) then it's an Object and can be handled as a generic Object.
The code might need to be tweaked to handle final, private, and protected fields, but you should be able to figure how to do that from the documentation.
Good luck with your legacy code!
Edit:
I forgot to mention, if the initial value stored in one of the static fields is mutated then simply caching it and restoring it won't do the trick since it will just re-assign the mutated object. I'm also assuming that you'll be able to expand on this code to work with an array of static classes rather than a single class.
Edit:
I've added a check for Cloneable objects to handle cases like the HashMap in your example. Obviously it's not perfect, but hopefully this will cover most of the cases you'll run in to. Hopefully there are few enough edge cases that it won't be too big of a pain to reset them by hand (i.e. add the reset code to the setUp() method).
Here's my two cents
1. Extract static reference into getters / setters
This works when you are able to create a subclass of it.
public class LegacyCode {
private static Map<String, Object> something = new HashMap<String, Object>();
public void doSomethingWithMap() {
Object a = something.get("Object")
...
// do something with a
...
something.put("Object", a);
}
}
change into
public class LegacyCode {
private static Map<String, Object> something = new HashMap<String, Object>();
public void doSomethingWithMap() {
Object a = getFromMap("Object");
...
// do something with a
...
setMap("Object", a);
}
protected Object getFromMap(String key) {
return something.get(key);
}
protected void setMap(String key, Object value) {
seomthing.put(key, value);
}
}
then you can get rid of dependency by subclass it.
public class TestableLegacyCode extends LegacyCode {
private Map<String, Object> map = new HashMap<String, Object>();
protected Object getFromMap(String key) {
return map.get(key);
}
protected void setMap(String key, Object value) {
map.put(key, value);
}
}
2. Introduce static setter
This one should be pretty obvious.
public class LegacyCode {
private static Map<String, Object> something = new HashMap<String, Object>();
public static setSomethingForTesting(Map<String, Object> somethingForTest) {
something = somethingForTest;
}
....
}
Both ways are not pretty, but we can always come back later once we have tests.
I have the following factory class. It has two methods which take Class instances and return the corresponding object. They have the same method name, and both methods take Class as parameter but with different generic class, also return different types. Does the compiler think these two methods as duplicate? When I open the java file in Eclipse, it reports errors like:
Description Resource Path Location Type
Method lookupHome(Class) has the same erasure lookupHome(Class) as another method in type EJBHomeFactory EJBHomeFactory.java
However, it seems the javac won't report any error on it.
import javax.ejb.EJBHome;
import javax.ejb.EJBLocalHome;
public class EJBHomeFactory {
public <T extends EJBHome> T lookupHome(Class<T> homeClass) throws PayrollException {
return lookupRemoteHome(homeClass);
}
public <T extends EJBLocalHome> T lookupHome(Class<T> homeClass) throws PayrollException {
return lookupLocalHome(homeClass);
}
/* ... define other methods ... */
}
Update 1: Here is the ant script that makes the code pass, I'm not sure how it works, but it doesn't throw any errors. It seems the compiler is Eclipse JDT Compiler, I tried with the regular javac, and it doesn't compile.
<target name="compile" depends="init" description="Compile Java classes">
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
<mkdir dir="${build.classes.dir}"/>
<javac destdir="${build.classes.dir}"
srcdir="${build.src.dir};${devsrc.dir}"
deprecation="${build.deprecation}"
debug="${build.debug}"
source="${build.source}"
target="${build.target}"
nowarn="${suppress.warning}"
bootclasspath="${bootclasspath}" >
<classpath>
<path refid="build.class.path.id"/>
</classpath>
</javac>
</target>
Update 2: I just create another example, have two base classes, and have two subclasses, a factory class takes Class and generate instance based on the parameter's type. The code can't be compiled by javac, and in Eclipse, the IDE complains about the same erasure problem. Here is the code:
Two empty base classes:
public class BaseClassFirst {
}
public class BaseClassSecond {
}
Two subclasses:
public class SubClassFirst extends BaseClassFirst {
private int someValue = 0;
public SubClassFirst() {
System.out.println(getClass().getName());
}
public SubClassFirst(int someValue) {
this.someValue = someValue;
System.out.println(getClass().getName() + ": " + this.someValue);
}
}
public class SubClassSecond extends BaseClassSecond {
private int someValue = 0;
public SubClassSecond() {
System.out.println(getClass().getName());
}
public SubClassSecond(int someValue) {
this.someValue = someValue;
System.out.println(getClass().getName() + ": " + this.someValue);
}
}
Factor class:
import java.lang.reflect.Method;
public class ClassFactory {
private static ClassFactory instance = null;
private ClassFactory() {
System.out.println("Welcome to ClassFactory!");
}
public static synchronized ClassFactory getInstance() {
if (instance == null) {
instance = new ClassFactory();
}
return instance;
}
public <T extends BaseClassFirst> T createClass(Class<T> firstClazz) {
if (firstClazz.equals(SubClassFirst.class)) {
try {
return firstClazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
public <T extends BaseClassSecond> T createClass(Class<T> secondClazz) {
if (secondClazz.equals(SubClassSecond.class)) {
try {
return secondClazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
ClassFactory factory = ClassFactory.getInstance();
SubClassFirst first = factory.createClass(SubClassFirst.class);
SubClassSecond second = factory.createClass(SubClassSecond.class);
for (Method method : ClassFactory.class.getDeclaredMethods()) {
System.out.println(method);
}
}
}
This works when the method can be resolved at compile time because the return type is part of the signature. After erasure you have two methods
public EJBHome lookupHome(Class homeClass) throws PayrollException;
public EJBLocalHome lookupHome(Class homeClass) throws PayrollException;
You cannot define these without generics but as the return type is part of the signature, these are different methods.
You can call
lookupHome(EJBHome.class);
lookupHome(EJBLocalHome.class);
but not
Class c= EJBHome.class;
lookupHome(c); // Ambiguous method call.
EDIT: Try the following.
for (Method method : EJBHomeFactory.class.getDeclaredMethods()) {
System.out.println(method);
}
And you should see something like
public javax.ejb.EJBHome EJBHomeFactory.lookupHome(java.lang.Class)
public javax.ejb.EJBLocalHome EJBHomeFactorylookupHome(java.lang.Class)
Similarly, if you use javap -c.
invokevirtual #8; //Method lookupHome:(Ljava/lang/Class;)Ljavax/ejb/EJBHome;
invokevirtual #10; //Method lookupHome:(Ljava/lang/Class;)Ljavax/ejb/EJBLocalHome;
EDIT If you want an example of where the return type is part of the signature..
class A {
public static Byte getNum() { return 0; }
}
class B {
public static void main(String ... args) {
int i = A.getNum();
System.out.println(i);
}
}
Compile and run this and you get no error, now change the signature of getNum in A to
class A {
public static Integer getNum() { return 0; }
}
and compile only the class A. If the return type was not part of the signature, this would make no difference to B, however if you run B without recompiling it you get
Exception in thread "main" java.lang.NoSuchMethodError: A.getNum()Ljava/lang/Byte;
at B.main(B.java:10)
As you can see, the return type Ljava/lang/Byte; is the inetrnal name of the return type and part of the signature.
Return type isn't part of a signature.
With generics, the two methods do have different argument types, so compiler should be able to separate them. Checking the current language spec, the two methods should be allowed. I heard that in Java 7, they will not be allowed, which is pretty bad in theoretical sense.
To answer your question, yes, they do have different signatures, based on argument types.
But practically, you should avoid such confusion anyway. Have two different method names.
public <T extends EJBHome> T lookupHome(Class<T> homeClass)
public <T extends EJBLocalHome> T lookupLocalHome(Class<T> localHomeClass)
Overloading is never necessary. When in doubt, break overloading by using different names.
These are duplicate methods. Type erasure means that Class<T> is reduced to Class at runtime, which means that you have two methods that each have the signature lookupHome(Class homeClass). My understanding is that the compiler should not compile this code; if you have a version of javac that compiles it, then something is wrong!
Your best bet is to rename both methods so that they each have a more specific name than lookupHome.
EDIT: After poking around in the language spec for a while, I think it is very possible that the declaration is legal, although I'm not 100% sure. I still think it's a bad idea to have two methods with identical signatures after erasure.