简体   繁体   中英

Using raw type with interface in Java

I'm trying to find information about raw types and is it possible to use with interface following way:

public class GlobalConverter {

    public interface Listener {
        void onReady(Object t);
    }

    public void convert(String string, Class<?> resultClass, Listener listener) {
        try {
            listener.onReady(resultClass.newInstance());
        } catch (IllegalAccessException e) {
        } catch (InstantiationException e) {
        }
    }

    public void test() {
        convert("Test", MyClass.class, new Listener() {

            @Override
            public void onReady(Object object /* Possible to be MyClass object ? */) {
            }
        });
    }
}

What I'm trying to achieve would be like above, but for the end user the onReady callback would return the resultClass type of object. Any hints/explanations highly appreciated.

Thanks.

I'll make the Listener itself generic:

public interface Listener<T> {
    void onReady(T t);
}

And then the convert method should also be generic:

public <T> void convert(String string, Class<T> resultClass, Listener<T> listener) {
    try {
        listener.onReady(resultClass.newInstance());
    } catch (IllegalAccessException e) {
    } catch (InstantiationException e) {
    }
}

And call it like:

convert("Test", MyClass.class, new Listener<MyClass>() {
        @Override
        public void onReady(MyClass object) {
        }
    });

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