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

1k views Asked by At

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?

2

There are 2 answers

1
Yuriy Nakonechnyy On BEST ANSWER

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...

0
tdrury On

worst case you can always use JBlock.directStatement()...