문제

I have following class hierarchy:

public abstract class Property<T>
{
    private long id;
    private String name;
    private T value;

    /*setters and getters*/
}

public class NumberProperty extends Property<Integer>

public class TextProperty extends Property<String>

...and a class containing List<Property> properties. I get "Property is raw type. References to generic type Property<T> should be parametrized". I know why, but I want to have one list of properties of few, known types (Property cannot be instatiated as it is abstract class).

My question is: can I ignore the warning or should I change my code (how?) ?

도움이 되었습니까?

해결책

Use Property<?> if you don't care about which type of object it is this will instruct the compiler that you know what you are doing.

List<Property<?>> list;

다른 팁

Collections in Java are homogeneous, so it is an error to put values of varying types into them. Note that Property<Integer> is not hierarchically related to Property<String>—these are two disparate types and the Java type system will not be able to represent your list where some properties are strings and some integers. Your only option is to lose type safety.

Since it's a warning, you can always choose to ignore it ;).

The warning informs you that when you have a List<Property>, you don't know what comes for the <T> in the Property class. If you're not sure, you can use List<Property<?>> to indicate that anything will do.

Refer to Oracles generics tutorial to learn more on this topic.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top