开发者

Error Generic Method in java

package com.openwaf.test.basic;
public class MethodArgumentTest {
    static interface Inf{}
    static class One<E extends Inf > implements Inf{
        public <T extends One> T get(T k){
        开发者_开发百科    return k;
        }
    }
    static class Two<E extends Inf> extends One<E>{ }
    public static void test(){
        One o=new One<Inf>();
        Two t=new Two<One>();
        o.<Two>get(t);
    }
}

Above code is just for testing purpose. IMHO it should compile without any problem ,but java compiler says

MethodArgumentTest.java:15: get(com.openwaf.test.basic.MethodArgumentTest.One) in com.openwaf.test.basic.MethodArgumentTest.One cannot be applied to (com.openwaf.test.basic.MethodArgumentTest.Two)

o.get(t);

1 error

Can someone please help me out here ?


Ok, as you said this is for testing only I will not ask what this code is good for. The following one compiles but still produces a warning. You were not consequent enough defining the generics:

public class MethodArgumentTest {
    static interface Inf {
    }

    static class One<E extends Inf> implements Inf {
        public <T extends One<E>> T get(T k) {
            return k;
        }
    }

    static class Two<E extends Inf> extends One<E> {
    }

    public static void test() {
        One<Inf> o = new One<Inf>();
        Two<One<Inf>> t = new Two<One<Inf>>();

        o.<Two> get(t); /* unchecked warning */
    }
}


I think what you need to do is

Two tPrime= o.get(t);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜