Search code examples
javaarrayssun-codemodel

CodeModel How do i get value at specific index with com.sun.codemodel


I'm using com.sun.codemodel for generating my classes. I need to dynamically get array value depending on index argument.

So i have an invocation that suppose to return an array

 JcodeModel model = new JCodeModel();
 JPackage jPackage = codeModel._package(packageName);
     .....
 JType personType = codeModel._ref(Person.class);
 jVar personObject = method.decl(personType, "person", JExpr._new(personType));
 personObject.invoke("getRoles");???

In this case getRoles() returns an array and i want to get an object at a specific index. Something like this

int index = 0;
Person person = new Person();
String role = person.getRoles()[index];

What should i do?


Solution

  • Don't know whether I'm right, but maybe following will work for you:

    JInvocation invocation = personObject.invoke("getRoles");
    JArrayCompRef arrayCompRef = invocation.component(indexExpression);
    

    Found this in following JavaDoc: http://codemodel.java.net/nonav/apidocs/com/sun/codemodel/JExpressionImpl.html#component(com.sun.codemodel.JExpression)

    Hope this helps...