jaxb-codemodel icon indicating copy to clipboard operation
jaxb-codemodel copied to clipboard

generating generic method

Open glassfishrobot opened this issue 14 years ago • 5 comments

Problem is generating a generic method like: public <T> T foo(..)

{..}

The problem is in instantiating a JTypeVar.

Making the constructor public would solve my problem as follows: JTypeVar Ttype = new JTypeVar(codeModel, "T"); JMethod fooMethod = someClass.method(JMod.PRIVATE, Ttype, "foo"); fooMethod.generify("T");

Can you please make the constructor public or introduce some factory method or give me a hint how to generate generic methods, otherwise?

glassfishrobot avatar Jul 12 '11 11:07 glassfishrobot

Reported by hubert_wagener

glassfishrobot avatar Jul 12 '11 11:07 glassfishrobot

mattbenson said: I have a method:

JType naiveType(String name) { try

{ return codeModel.parseType(name); }

catch (ClassNotFoundException e)

{ return codeModel.directClass(name); }

}

if I, e.g., pass "T" to this method and use the resulting JType as the return value of my method, presumably the directClass() execution path is taken, and the final code output seems to do what I want.

glassfishrobot avatar Feb 03 '12 21:02 glassfishrobot

july said: I need the same feature too, thanks.

glassfishrobot avatar Apr 09 '12 12:04 glassfishrobot

johncarl81 said: It turns out that this is possible with CodeModel as it stands. Here's an example from a post on StackOverflow:

http://stackoverflow.com/q/9355160/654187

final JDefinedClass exampleClass = codeModel._class( "com.example.ExampleClass" ); final JMethod method = exampleClass.method( JMod.PUBLIC, Object.class, "getValue" ); final JTypeVar t = method.generify( "T" ); method.type( t ); method.param( codeModel.ref( Class.class ).narrow( t ), "type" ); method.body()._return(JExpr._null());

produces:

package com.example;

public class ExampleClass {

public<T >T getValue(Class<T> type)

{ return null; }

}

Thanks to ajlane for figuring this one out.

glassfishrobot avatar May 01 '12 03:05 glassfishrobot

This issue was imported from java.net JIRA CODEMODEL-4

glassfishrobot avatar Apr 24 '17 07:04 glassfishrobot