Question

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.

Was it helpful?

Solution

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) {
        }
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top