Reputation: 1819
I'm trying to use the Java CodeModel library to generate some code. In my generated code I need to perform a type cast. I want something like this...
foo.setBar( ((TypeCastToThis)someVariable).getBar() );
The only support I've found in the library is by using JCast JExpr.cast(JType type, JExpression expr). However according to Eclipse the return type, JCast, is not public. The exact error is: "The type com.sun.codemodel.JCast is not visible".
Here's a simple example of what I'm doing.
import java.io.File;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JCast; //<-- Eclipse flags this as an error
import com.sun.codemodel.JClass;
import com.sun.codemodel.JClassAlreadyExistsException;
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.JVar;
public class CastTest
{
public static void main(String[] args) throws JClassAlreadyExistsException
{
// TODO Auto-generated method stub
JCodeModel codeModel = new JCodeModel();
JDefinedClass testClass = codeModel._class("MyTestClass");
JMethod testMeth = testClass.method(JMod.PUBLIC, codeModel.VOID, "TypeCastTestMethod");
JBlock testMethBody = testMeth.body();
JVar castMeVar = testMethBody.decl(codeModel.INT, "castMe", JExpr.lit(42));
JClass typeCastToThisClass = codeModel.directClass("TypeCastToThis");
JCast castResult = JExpr.cast(typeCastToThisClass, castMeVar);
testMethBody.decl(typeCastToThisClass, "theTypeCastedObject", castResult);
codeModel.build(new File("/path/to/output/directory"));
}
/*
The generated code should look like this.
public void TypeCastTestMethod()
{
int castMe = 42;
TypeCastToThis theTypeCastedObject = (TypeCastToThis)castMe;
}
*/
}
Am I using the library incorrectly and/or is there another way to achieve my goal?
Upvotes: 2
Views: 1874
Reputation: 1819
In case anyone else has this issue later it can be by-passed by using implicit upcasting to a JExpression from a JCast on the return value of JExpr.cast(....). JCast is a subtype of JExpression.
From....
JCast castResult = JExpr.cast(typeCastToThisClass, castMeVar);
To.....
JExpression castResult = JExpr.cast(typeCastToThisClass, castMeVar);
Upvotes: 7