How do I set up an inferred type list getter and setter?

199 views Asked by At
List<T> objectList = null;
public <T> List<T> getObjectList() { return this.objectList; }
public <T> void setObjectList(List<T> objList) { this.objectList = objList; }

The problem appears to be the field declaration. Semantically, I am wondering why, since the goal is to infer the type, this doesn't work.

From a short term gain point of view, I just want something that works.

Icing on the cake would be if someone would point me to a detailed, i.e. in-depth, discussion of inferred types with examples.

The context is a raw string returned from a request-reply bus message that needs to be de-serialized into a list of like javabean objects. I realize I could just create a marker interface and make all of my javabeans impl it, however, that seems like kind of a wanky solution to me.

JDK 1.6 (no chance of moving up to 7 or 8)

1

There are 1 answers

0
Bohemian On BEST ANSWER

You have typed your methods... don't - remove <T> from the get/set methods:

public List<T> getObjectList() { return this.objectList; }
public void setObjectList(List<T> objList) { this.objectList = objList; }

When you code

public <T> List<T> getObjectList() { return this.objectList; }
public <T> void setObjectList(List<T> objList) { this.objectList = objList; }

The initial <T> declares a type for the scope of the method call, and you have used the same name for the generic parameter as your class, so the method type hides the class type.

Had you coded:

public <X> List<T> getObjectList() { return this.objectList; }
public <X> void setObjectList(List<T> objList) { this.objectList = objList; }

It would have worked too. Of course the X generic parameter would have been ignored, but at least it would have been obvious that it was unnecessary.