2

I need to generate a generic method like

public static <T extends SomeObject> T get(Class<T> type) {
    ...
    return null;
}

Anybody done this before?

abedurftig
  • 1,118
  • 1
  • 12
  • 24

1 Answers1

2

The key is the JMethod#generify method:

import com.sun.codemodel.CodeWriter;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;
import com.sun.codemodel.writer.SingleStreamCodeWriter;

public class CreateGenericMethodTest
{
    public static void main(String[] args) throws Exception
    {
        JCodeModel codeModel = new JCodeModel();
        JPackage jpackage = codeModel._package("com.example");
        JDefinedClass jclass = jpackage._class("Example");

        JType genericType = codeModel.directClass("T");
        JMethod jmethod =
            jclass.method(JMod.PUBLIC | JMod.STATIC, genericType, "get");
        jmethod.generify("T", Number.class);
        JClass parameterType = codeModel.ref(Class.class).narrow(genericType);
        jmethod.param(parameterType, "type");

        jmethod.body()._return(JExpr.ref("null"));
        CodeWriter codeWriter = new SingleStreamCodeWriter(System.out);
        codeModel.build(codeWriter);
    }
}

Output:

package com.example;

public class Example {

    public static<T extends Number >T get(Class<T> type) {
        return null;
    }

}

(I used Number as the bound, but you can choose it arbitrarily)

Marco13
  • 53,703
  • 9
  • 80
  • 159
  • If you have to generate multiple generic methods and you want to use the same `T` name, then save the class off in a value somewhere to access again. The second time you try to generate a method on the same model with class name "T" wont work otherwise. However, this method also won't generate two methods with a generic type T that are narrowed by different types – Decoded Oct 11 '18 at 22:14