다른 제네릭 클래스에서 유형 매개 변수로도 사용될 때 제네릭 유형을 추론 할 수 없습니다.

Vejto

아래 코드를 고려하십시오. withoutCastTest가 아닌 withCastTest에서 String으로 캐스팅해야하는 이유는 무엇입니까?

유형 매개 변수가 다른 제네릭 클래스에서 유형 매개 변수로 사용될 때 Java가 제네릭 클래스를 추론 할 수없는 것 같습니다. withoutCastTest에서는 유형 매개 변수를 일반 매개 변수로 보내고 올바른 유형을 추론 할 수 있습니다. 왜 그런 겁니까? 어쨌든 주변?

질문이 이상하게 공식화되어 있으면 명명 규칙에 대해 잘 모르겠습니다.

public class RandomHelper {

    public interface RandomInterface<E> {
        public abstract E get();
    }

    public static abstract class Randomable<E> implements RandomInterface {

        protected E object;

        public Randomable(E object) {
            this.object = object;
        }

    }

    public static <E> E withCastTest(RandomInterface<E> action) {
        E savedObject = action.get();
        return savedObject;
    }

    public static <E> E withoutCastTest(RandomInterface<E> action, E e) {
        E savedObject = action.get();
        return savedObject;
    }

}

public class TestJava {

    public void run() {
        String s ="test";
        String ret = (String) RandomHelper.withCastTest(new Randomable<String>(s) {

            @Override
            public String get() {
                return object;
            }
        });

        String ret2 = RandomHelper.withoutCastTest(new Randomable<String>(s) {

            @Override
            public String get() {
                return object;
            }
        }, "test2");

        System.out.println(ret);
        System.out.println(ret2);

    }

    public static void main(String[] args) {
        TestJava test = new TestJava();
        test.run();
    }

}

편집 : 코드의 오타

나일 강

<E>다음 implements RandomInterface매개 변수를 추가하기 만하면 됩니다.

public abstract class Randomable<E> implements RandomInterface<E> {

그런 다음 변경해야합니다. ( get메소드 의 반환 유형에 유의하십시오 )

    String ret = RandomHelper.withCastTest(new Randomable<String>(s) {

        @Override
        public String get() {
            return s;
        }
    });

    String ret2 = RandomHelper.withoutCastTest(new Randomable<String>(s) {
        @Override
        public String get() {
            return s;
        }
    }, "test2");

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관