Hector
Hector

Reputation: 5428

How to assign a value to a specific index of an array with Java codeModel

How do you employ com.sun.codemodel to generate this java statement?

constructorArgs[constructorArgIndex] = null;

I tried using com.sun.codemodel.JArrayCompRef via component() however i get com.sun.codemodel.JArrayCompRef is not visible when trying to call method assign()

As com.sun.codemodel.JArrayCompRef is declared as follows:-

final class JArrayCompRef extends JExpressionImpl

implements JAssignmentTarget

Upvotes: 1

Views: 506

Answers (2)

Hector
Hector

Reputation: 5428

Anybody else wants to know this is what i endended up doing...

final JDefinedClass jDefindedClass = codeModel._class(JMod.PUBLIC, "org.sand.pit", ClassType.CLASS);
final JMethod jmethod = jDefindedClass.method(JMod.PUBLIC, void.class, "testMethod");
final JBlock jblock = jmethod.body();

final JExpression equalsZero = JExpr.lit(0);
final JVar jvarIndex = jblock.decl(JMod.FINAL, codeModel.parseType("int"), "arrayIndex", equalsZero);

final JExpression getArraySize = JExpr.lit(100);
final JClass wildcardClass = codeModel.ref("java.lang.Class");
final JArray newClassArray = JExpr.newArray(wildcardClass, getArraySize);
final JVar jvar = jblock.decl(JMod.FINAL, wildcardClass.array(), "parameterTypes", newClassArray);

final JAssignmentTarget theArray = JExpr.ref("parameterTypes").component(jvarIndex);
jblock.assign(theArray, JExpr._null());

This generates the folloiwng java

    public void testMethod() {
    final int arrayIndex = 0;
    final Class[] parameterTypes = new Class[ 100 ] ;
    parameterTypes[arrayIndex] = null;
}

Upvotes: 0

John Ericksen
John Ericksen

Reputation: 11113

.component() is available via the JExpression interface. All you need to do is use it via the interface:

JExpression expression = ...
expression.component(JExpr.lit(1));

This works for the other common expressions in JCodeModel (JVar, JInvocation) as they all extend JExpression.

I ran into a similar problem when trying to use this method and casing the expression to a JArrayCompRef.

Upvotes: 2

Related Questions