简体   繁体   中英

Casting from Non-generic base class to Generic Sub class

I have non-generic parent class.

public class FilterCondition {

    private String key;

    private String value;

    private String  condition;
}

And I have a generic subclass.

public class FilterJoinCondition<P,S> extends FilterCondition {
    public FilterJoinCondition(String key, String value, String condition) {
        super(key, value, condition);
    }

    private Class primaryEntity;

    private Class secondaryEntity;

    private String mappedBy;
}

I store all the FilterCondition in a List and pass to a method where I need the types passed to the FilterJoinCondition

if (condition instanceof FilterJoinCondition) {
     FilterJoinCondition<P,S>  joinCondition = (FilterJoinCondition) condition;
}

I know this is not correct (above code).

How could I cast FilterCondition without knowing the types (P,S)?

You can just use the ? placeholder. Obviously you won't be able to do things with the new joinCondition , that requires knowledge of the specific Types. But all the general stuff you can do just fine.

public class FilterJoinCondition<P,S> extends FilterCondition {

    private Class primaryEntity;

    private Class secondaryEntity;

    private String mappedBy;
    
    public FilterJoinCondition(String key, String value, String condition) {
        super(key, value, condition);
    }
    
    public void doStuff(P param) {
        System.out.println(param.getClass());
    }
    
    public static void main(String[] args) {
        FilterCondition condition = new FilterJoinCondition<>("foo", "bar", "baz");
        
        if (condition instanceof FilterJoinCondition) {
             FilterJoinCondition<?,?>  joinCondition = (FilterJoinCondition) condition;
             joinCondition.doStuff(new String()); //illegal, you do not know P!
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM