Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
package lambdas;
import sun.reflect.ConstantPool;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class TypeTest {
public static interface Block<A> {
public void call(A arg);
private static final Method getConstantPool;
static {
try {
getConstantPool = Class.class.getDeclaredMethod("getConstantPool");
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
public static <A> void instantitesLambdaArgBasedOnGenericType(Block<A> block) throws Exception {
Type genericInterface = block.getClass().getGenericInterfaces()[0];
if (genericInterface instanceof ParameterizedType) {
Class<A> type = (Class<A>) ((ParameterizedType) genericInterface).getActualTypeArguments()[0];;
} else {
// Code from @danielbodart. AMAZING.
ConstantPool constantPool = (ConstantPool) getConstantPool.invoke(block.getClass());
String[] methodRef = constantPool.getMemberRefInfoAt(20);
int argumentIndex = 0;
String argumentType =[2])[argumentIndex].getClassName();
Class<A> type = (Class<A>) Class.forName(argumentType);;
public static class Thing {
public static void main(String[] args) throws Exception {
// Generic arg = class lambdas.TypeTest$Thing
instantitesLambdaArgBasedOnGenericType((Thing message) -> System.out.println(message.getClass()));
// Generic arg = class lambdas.TypeTest$Thing
instantitesLambdaArgBasedOnGenericType((Block<Thing>) (Thing message) -> System.out.println(message.getClass()));
// Generic arg = class lambdas.TypeTest$Thing
instantitesLambdaArgBasedOnGenericType(new Block<Thing>() {
public void call(Thing message) {

This comment has been minimized.


This comment has been minimized.

Copy link

@tomekl007 tomekl007 commented Dec 4, 2014

i've add similar functionality to typesafe-akka library, see my commit :

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