Skip to content

Instantly share code, notes, and snippets.

@uberto
Created December 2, 2018 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uberto/c37970ba1d3b49c61568809085a84d1f to your computer and use it in GitHub Desktop.
Save uberto/c37970ba1d3b49c61568809085a84d1f to your computer and use it in GitHub Desktop.
Create and export anonymous classes
package com.gamasoft.memoryReferences;
import java.util.Observable;
public class Factory {
public Runnable createRunnable() {
return new Runnable() {
@Override
public void run() {
System.out.println("run");
}
};
}
static public Runnable createStaticRunnable() {
return new Runnable() {
@Override
public void run() {
System.out.println("run");
}
};
}
}
@uberto
Copy link
Author

uberto commented Dec 2, 2018

Verify the presence of inner field with this test

`
package com.gamasoft.memoryReferences;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.junit.Assert.*;

public class FactoryTest {

@Test
public void instanceFactory() throws NoSuchFieldException, IllegalAccessException {
    Factory myFactory = new Factory();

    Runnable r = myFactory.createRunnable();

    Field field = r.getClass().getDeclaredField("this$0");
    field.setAccessible(true);
    System.out.println("segret field: " + field.get(r).getClass());
}

@Test
public void staticFactory() throws NoSuchFieldException, IllegalAccessException {

    Runnable r = Factory.createStaticRunnable();

    Field field = r.getClass().getDeclaredField("this$0");
    field.setAccessible(true);
    System.out.println("static segret field: " + field.get(r).getClass());
}

}
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment