How to fix bug found by findbugs "Method accesses list or array with constant index"

Viewed 3625

java code:

p.setCode((String) fileds[1]);
p.setTitle((String) fileds[2]);
p.setLogo((String) fileds[3]);
p.setMaxBorrowAmt((Integer) fileds[4]);
p.setMinBorrowAmt((Integer) fileds[5]);

fileds[] is Object array,it's created by Spring-Data-JPA to select something from 3 different tables;

@Query(
   value="select a.id,a.code,b.title,b.logo,c.max from tableA a left join TableB b left join TableC c where ... ",
   nativeQuery = true
)
List<Object[]> findSomething();

findbugs warning:

Method accesses list or array with constant index

This method accesses an array or list using a constant integer index. Often, this is a typo where a loop variable is intended to be used. If however, specific list indices mean different specific things, then perhaps replacing the list with a first-class object with meaningful accessors would make the code less brittle.

how should I fix this bug?

2 Answers

Use a final Integer Constant instead

public static final Integer CODE_POSITION = 0;

//other code

p.setCode((String) fileds[CODE_POSITION]);

//rest of the code...

Create Custom Class

public class CustomClass{
private String code;
private String title;
// rest goes here 
//all setter getter 
}

and then replace method signature List<Object[]> findSomething(); with List<CustomClass> findSomething();

And Access the listItem using below code snap.

p.setCode(listItem.getCode());
p.setTitle(listItem.getTitle());
Related