Invoking public method on a class in a different package via reflection

Posted by KARASZI István on Stack Overflow See other posts from Stack Overflow or by KARASZI István
Published on 2012-10-04T15:32:54Z Indexed on 2012/10/04 15:37 UTC
Read the original article Hit count: 224

Filed under:
|
|

I ran into the following problem.

I have two different packages in package a I would like to call the implemented method of an interface in a package b but the implementing class has package visibility.

So a simplifed code looks like this:

package b;

public final class Factory {
    public static B createB() {
        return new ImplB();
    }

    public interface B {
        void method();
    }

    static class ImplB implements B {
        public void method() {
            System.out.println("Called");
        }
    }
}

and the Invoker:

package a;

import java.lang.reflect.Method;
import b.Factory;
import b.Factory.B;

public final class Invoker {
    private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[] {};
    private static final Object[] EMPTY_OBJECT_ARRAY = new Object[] {};

    public static void main(String... args) throws Exception {
        final B b = Factory.createB();
        b.method();

        final Method method = b.getClass().getDeclaredMethod("method", EMPTY_CLASS_ARRAY);
        method.invoke(b, EMPTY_OBJECT_ARRAY);
    }
}

When I start the program it prints out Called as expected and throws an Exception because the package visibility prohibits the calling of the discovered method.

So my question is any way to solve this problem? Am I missing something in Java documentation or this is simply not possible although simply calling an implemented method is possible without reflection.

© Stack Overflow or respective owner

Related posts about java

Related posts about reflection