emmby
emmby

Reputation: 100464

How to instantiate a non-public final class using reflection?

I have a non-public final class that looks like the following:

final class FragmentManagerImpl {
    ...
}

Note that it is not public and it has no declared constructors.

I would like to instantiate an instance of this class using reflection. However, both of the following code snippets result in IllegalAccessExceptions:

        // BUG IllegalAccessException on calling newInstance
        final Class c = Class.forName("android.support.v4.app.FragmentManagerImpl");
        c.newInstance();

        // BUG IllegalAccessException on calling newInstance
        final Class c = Class.forName("android.support.v4.app.FragmentManagerImpl");
        final Constructor constructor = c.getDeclaredConstructor();
        constructor.setAccessible(true);
        constructor.newInstance();

What is the correct way to instantiate this class from a package that is not android.support.v4.app?

Upvotes: 5

Views: 3402

Answers (3)

emmby
emmby

Reputation: 100464

Hm, it appears to have been user error. Using the constructor method outlined in the question does seem to have worked properly.

Upvotes: 0

n0rmzzz
n0rmzzz

Reputation: 3848

According to JavaDocs, you can call getDeclaredConstructors() method and you'll get all the private constructors as well as the default constructor.

public Constructor[] getDeclaredConstructors() throws SecurityException

Returns an array of Constructor objects reflecting all the

constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors. The elements in the array returned are not sorted and are not in any particular order. If the class has a default constructor, it is included in the returned array. This method returns an array of length 0 if this Class object represents an interface, a primitive type, an array class, or void.

See The Java Language Specification, section 8.2.

It doesn't specify how exactly this getDeclaredConstructor(Class... parameterTypes) method, that you are using, will work though.

Upvotes: 3

Stephen C
Stephen C

Reputation: 718826

I'm guessing, but I think that it is complaining about the accessibility of the class not (just) the constructor.

Try calling setAccessible(true) on the Class object as well as the Constructor object.

Upvotes: 0

Related Questions