Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this java generic cast?

Tags:

java

How can I make this java generic cast ?

public interface IField {

}


class Field implements IField { // package private class

}

public class Form {
  private List<Field> fields;


  public List<IField> getFields() {
    return this.fields;

  }

}

The return statement throws a compiler error (I know the reason - I read the generics tutorial) but it would be very handy to write such code.

If I declared "fields" as List I would need to use a lot of casts to Field in other methods of a Form class .

Can I force that damn compiler to bend it's rules and compile that return statement ?

Thanks in advance.

like image 570
Łukasz Bownik Avatar asked Nov 24 '08 13:11

Łukasz Bownik


2 Answers

A better solution, IMO, is to change the signature of your method to use a bounded wildcard:

public List<? extends IField> getFields()

This will let the caller treat anything coming "out" of the list as an IField, but it won't let the caller add anything into the list (without casting or warnings), as they don't know what the "real" type of the list is.

like image 193
Jon Skeet Avatar answered Oct 19 '22 09:10

Jon Skeet


As it happens, you can, because Java generics are just grafted on, not part of the type system.

You can do

return (List<IField>)(Object)this.fields;

because all List<T> objects are the same underlying type.

Bear in mind that this allows anyone to put any type implementing IField in your list, so if your collection is not read-only, you may run into difficulties.

like image 35
Sunlight Avatar answered Oct 19 '22 08:10

Sunlight