Instantiation an inner class using reflection

I want to instantiate an inner class using the Class.newInstance() method called within the Outer class constructor:
public Outer
public Outer()
Inner.class.newInstance();
private Class Inner { }
When I try it, however, I get an InstantiationException.
Is there some way to do this?
Thanks for the help.
Scott

Here is a consolidation of what everyone posted and it does appear to work. In one of your post you used the getDeclaredConstructors() method and said it was less than ideal; I am not sure what you meant but I suspect it was the hard coded array reference. Anyhow I used the getDeclaredConstructor() method which appears to get non-public constructors also and is basically the same as using the getConstructor() method.
import java.lang.reflect.*;
public class Test35 {
    static public void main(String[] args) {
        Test35 t35 = new Test35();
        t35.testIt();
    private class Inner {
        public String toString() {
            return "Hear I am";
    public void testIt() {
        try {
            Constructor con = Inner.class.getDeclaredConstructor(new Class[] {Test35.class});
            Inner in = (Inner)con.newInstance(new Object[] {this});
            System.out.println(in);
        } catch (Exception e) {
            e.printStackTrace();

Similar Messages

  • How to access private method of an inner class using reflection.

    Can somebody tell me that how can i access private method of an inner class using reflection.
    There is a scenario like
    class A
    class B
    private fun() {
    now i want to use method fun() of an inner class inside third class i.e "class c".
    Can i use reflection in someway to access this private method fun() in class c.

    I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
    Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
    So here's what it looks like:
            //list of inner classes, if any
            Class[] classlist = A.class.getDeclaredClasses();
            A outer = new A();
            try {
                for (int i =0; i < classlist.length; i++){
                    if (! classlist.getSimpleName().equals("B")){
    //skip other classes
    continue;
    //this is what I mention above.
    Constructor constr = classlist[i].getDeclaredConstructor(A.class);
    constr.setAccessible(true);
    Object inner = constr.newInstance(outer);
    Method meth = classlist[i].getDeclaredMethod("testMethod");
    meth.setAccessible(true);
    //the actual method call
    meth.invoke(inner);
    } catch (Exception e) {
    throw new RuntimeException(e);
    Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Instantiating member classes using reflection

    I have checked through this forum but if the answer to this question is here I missed it.
    I am trying to find out how to invoke the appropriate instantiation / constructor call to create an instance of a member class.
    The following works finepublic class Succeeds {
      public abstract static class AbstractMember {
      Succeeds(final AbstractMember am) {
      public static void main(final String[] args) {
        Succeeds a = new Succeeds (new Succeeds.AbstractMember () {
    }However I want to make the AbstractMember a real member class not a nested inner class and I want to instantiate the concrete subclass of AbstractMember in the constructor of Succeeds rather than outside the class. I tried the following:public class Fails {
      public abstract class AbstractMember {
        public class ConcreteMember extends AbstractMember {
      Fails(final Class<? extends AbstractMember> c)
        throws InstantiationException, IllegalAccessException {
        AbstractMember am = c.newInstance() ;
      public static void main(final String[] args)
        throws InstantiationException, IllegalAccessException {
        Fails a = new Fails (Fails.AbstractMember.ConcreteMember.class) ;
    }(Please forgive the appling treatment of exceptions, I wanted to make a small example). This compiles fine but fails at runtime with an InstantiationException I assume because the nullary constructor doesn't exist for a member class because of the need to make the connection to the containing object.
    So the question is is there a bit of reflection that allows me to achieve what I want?
    I cannot be the first person to try doing this. I am hoping it is doable otherwise I am going to have to make the design a bit yukky.
    Thanks.

    import java.lang.reflect.*;
    public class Fixed
        public abstract class AbstractMember
        public class ConcreteMember extends AbstractMember
        <T extends AbstractMember> Fixed(final Class<T> c) throws Exception
            Constructor<T> ctor = c.getConstructor(new Class[]{getClass()});
            AbstractMember am = ctor.newInstance(new Object[]{this});
        public static void main(final String[] args) throws Exception
            new Fixed(ConcreteMember.class);
    }My exception handling is even more lax than yours. Why isn't there a class ReflectionException? I moved ConcreteMember out of AbstractMember to keep things simple. It's not entirely necessary, but I didn't want to construct an AbstractMember first.

  • Inner classes use

    what is the main goal behind using inner classes in java design

    The best thing about inner classes in Java (something they missed in the C++ spec) is that a non-static inner class has direct access to everything in the containing class without the need to maintain an explicit reference.
    That makes inner class instances ideal as a kind of "delegate" from the main object into another context, e.g. to generate several ActionListener objects to be added to various gadgets, or as an Iterator which moves through some child elements.

  • Debugging Inner Class using jdb

    Hi
    I am using JDK 1.3.1 on solaris and observe that the java debugger does not stop at "Inner class" methods. Is there any way to make jdb (from command line) stop inside the "inner class"?

    I had the following code (similar to the example you gave) :
    package test;
    public class Outer {
      public Outer() {
        Inner i = new Inner();
      static public void main(String[] args) {
        Outer o = new Outer();
      public class Inner {
        public Inner() {
          System.out.println("Inner");
          Runnable Runner = new Runnable() {              
         public void run() {
           System.out.println("Runner");
          Runner.run();  
    }Which compiled into :
    Outer.class
    Outer$Inner.class
    Outer$1.class
    And to stop at the line System.out.println("Runner"); I could use stop at test.Outer$1:14 or stop in test.Outer$1.run(). So it seems that you need to look at the compiled .class name and use that.

  • Are inner classes used the same way as derived classes?

    Hi,
    I got myself a bit confused when I came across inner and derived classes.
    However, I know that the syntax for both are different.
    For inner classes:
    class OuterClass {
    class NestedClass {
    For inheritance:
    class ClassA {
    class ClassB extends ClassA {
    But I justed wanted to clarify if there's differences in the usage of either one?
    Thanks.

    Nat7 wrote:
    Hi,
    I got myself a bit confused when I came across inner and derived classes.
    However, I know that the syntax for both are different.That should be a clue. They are entirely different things.
    What this question suggests to me is that you don't understand what a derived class is or you don't understand what an inner class is.
    Perhaps if you gave us your definitions of them we could fix this.

  • Program Design Problem: Inner Class use verse interacting seperate classes?

    i am designing a GUI based program that needs to have 2+ windows that interact with each other. In my original design there were just two windows: the World display, and the tile choser (this is for 2D map editing). Because there were only 2, I made them both inner classes of another class. The top level class's fields were how I got the two windows to interact.
    Now I am adding more tile choser esque windows and it is getting very confusing and the amount of Fields is getting ridiculous and the whole thing isnt very OO.
    I thought about splitting up the World Display window and the Tile Choser window into two different classes and just have multiple instances of the Tile Choser class for the additional windows.
    The problem is the interaction. I could pass all of the variables that both classes require to constructers and set up lots and lots of get and set methods, but then that seems to destroy the whole idea of two classes. The whole project is getting really messy.
    Any thoughts?
    I know that was a jarbled explanation so just ask about any part that might be unclear

    Create an object that represents the state being manipulated. The model.
    Create methods to modify that data. Not getters/setters, but controllers. If it's a map, then maybe a method would be "addTown" or something. This represents the controller.
    Create methods to render the data graphically. The views.
    Pass this object to GUI widgets, or reference it from inner event handlers.

  • When  we going to use static inner class

    Hi
    when we r going use static inner class
    inner classes use for to create adaptorclasses that implement an interface.
    what about Static inner class
    if possible give some examples
    Thanks in adv

    static inner classes are used when the inner class does not require to access the encompassing class's variables/methods. By default non-static inner classes obtain a reference to the outer class instance through which they access the outer class variables and methods
    ram.

  • Passing Inner class name as parameter

    Hi,
    How i can pass inner class name as parameter which is used to create object of inner class in the receiving method (class.formane(className))
    Hope somebody can help me.
    Thanks in advance.
    Prem

    No, because an inner class can never have a constructor that doesn't take any arguments.
    Without going through reflection, you always need an instance of the outer class to instantiate the inner class. Internally this instance is passed as a parameter to the inner class's constructor. So to create an instance of an inner class through reflection you need to get the appropriate constructor and call its newInstance method. Here's a complete example:import java.lang.reflect.Constructor;
    class Outer {
        class Inner {
        public static void main(String[] args) throws Exception{
            Class c = Class.forName("Outer$Inner");
            Constructor cnstrctr = c.getDeclaredConstructor(new Class[] {Outer.class});
            Outer o = new Outer();
            Inner i = (Inner) cnstrctr.newInstance(new Object[]{o});
            System.out.println(i);
    }

  • Mapping inner class in mapping workbench

    A project needs to work with inner classes and map these inner classes using TopLink Mapping Workbench. Is this supported? Thanks.
    Haiwie

    Karen,
    Thanks for your response.
    I tried with 9.0.4.4, and it worked. I had to use 'Use Factory' option for Instantiation; the mapping workbench complains about the default instantiation setting, i.e. 'Use Default Constructor'.
    Haiwei

  • Problem during dynamic casting (using reflection)

    Hi Guys,
    Need you help
    Situation is like this �.I have a function which accept the Sting parameter
    Which is actually a full name of class �.using reflection I created the class and object
    Now I want to cast this newly created object to their original class type
    Code is somehow like this
    Public void checkThis (String name) throws Exception{
    Class c = Class.forName(name.trim());
    Object o = c.newInstance();     
    System.out.println(" class name = " + c.getName());
    throw ()o; //// here I want to cast this object to their orginal class type
    I tried throw (c.getName())o;
    But it is not working
    }

    You can't cast to an unknown type like that. You're trying to throw the object, which makes me believe you're loading and instantiating some Exception or other, right? Just cast the result to something generic, like Exception, or RuntimeException, or maybe Throwable. As long as the class you load actually is a subclass of whichever you choose, you'll be fine. And if it isn't, you've got problems anyway because you can't throw anything that isn't Throwable

  • Using reflection...

    Hi,
    I have one class. to run that, I am calling like the following...
    java -classpath ;.;\comdotebo; com.pack1.MyClass
    now I want to take the reference of this class(dynamically) using reflection pakcage like the following...
    Class cla = Class.forName("com.pack1.MyClass");
    but to take the class reference I need to set the classpath;
    so how can i set the classpath dynamically.
    please give proper solution
    thanks
    Raja Ramesh Kumar M

    here the case is we know both the class and the class path at run time only
    for ex: see the following.....
    I have two files .....
    1) c:\dir1\com\pack1\MyClass1.class
    2) c:\dir2\com\pack2\MyClass2.class
    now I want to access both the classes using reflection from ...
    c:\dir3\com\pack3\MainClass.class
    using reflection, we can write the following...
    Class clas1 = Class.forName("com.pack1.MyClass1");
    if I am taking like this, then I am getting ClassNotFoundException.
    becoz, for that we have to give the proper classpath before running the program.
    like.
    set classpath=%classpath%;.;c:\dir1;
    but my problem is here I know the the class name (for ex: com.pack1.MyClass1) and the classpath (ex: c:\dir1)
    at runtime only.
    so please tell me how to solve this problem
    regards
    Raja Ramesh Kumar

  • Generics and inner classes?

    How can I say my inner class uses the same type as it's genericised host class?
    Should I just not declare a "generic" type in the inner class?
    The code
    public class LinkedList<E> implements java.util.List<E>
      ... code omitted for brevity ...
       * An internal implementation of java.util.Iterator.
      private class Iterator<E> implements java.util.Iterator<E> {
        protected Node<E> current;
        public Iterator() {
          this.current = head; // error here
      ... code omitted for brevity ...
    produces the compiler error
    C:\Java\home\src\linkedlist\LinkedList.java:59: incompatible types
    found   : linkedlist.LinkedList.Node<E>
    required: linkedlist.LinkedList.Node<E>
          this.current = head;
                         ^I understand the meaning of the compiler error... it's effectively saying that "E" is not the same type within in the Iterator class as it is in the parent LinkedList class... What I don't understand is how to make E the same type within the Iterator... if I just leave the <E> off of Iterator<E> then it throws "unchecked operation" warnings... do I just have to put up with these warnings... but no that can't be right because java.util.LinkedList has an iterator and it's not throwing unchecked operation compiler warnings... so there has to be a way...
    Thanx all. Keith.

    One more dumbshit question...
    Is there a way to do this without the warnings OR the @SuppressWarnings({"unchecked"})
       * Returns the index of the last occurrence of the specified element in this
       * list, or -1 if this list does not contain the element.
      //@SuppressWarnings({"unchecked"})
      public int lastIndexOf(Object object) {
        int i = 0;
        int last = -1;
        for(Node<E> node=this.head.next; node!=null; node=node.next) {
          if (node.item.equals((E) object)) {
            last = i;
          i++;
        return(last);
    produces the warning
    C:\Java\home\src\linkedlist\LinkedList.java:313: warning: [unchecked] unchecked cast
    found   : java.lang.Object
    required: E
          if (node.item.equals((E) object)) {
                                   ^... remembering that List specifies +public int lastIndexOf(Object object);+ as taking a raw Object, not E element, as I would have expected.
    Thanx all. Keith.

  • Update problem when using reflection

    We have an issue when updating objects. The values are not updated in the DB when we set the values in the domain class using reflection. However when we explicitly set the values using the setter methods, update is ok.
    Here is the code for the reflection mechanism:
    UnitOfWork uow = session.acquireUnitOfWork();
    //domain class which needs to be persisted
    Student student = new Student();
    //get the clone
    Student studentClone = (Student) uow.registerObject(student);
    //copy the values from the value object into the
    // domain class using reflection
    studentClone.setVo(studentVo);
    uow.commit();
    The setVo method uses reflection to set the values (using invokeMethod). The values are set properly in the domain object. But the values are not updated when we do the commit.
    However, if we explicitly set the values in the clone using the "setter" methods, update is okay. So this code works fine.
    UnitOfWork uow = session.acquireUnitOfWork();
    Student student = new Student();      
    Student studentClone = (Student) uow.registerObject(student);
    studentClone.setName("NBA"); //set the value of name
    uow.commit();
    Any ideas would be appreciated...
    Thanks much

    TopLink 10.1.3 tracks changes through working and backup copies by default, so even if you set your changes through reflection they should be picked up. If you were using CMP 2 or EJB 3 or explicitly enabled AttributeChangeTracking, then changes set through reflective field access could be missed. In this case you should use the set methods through reflection, instead of the field directly.
    I would check your code that set the changes through reflection, perhaps it is not working as you expect. Check the state of the object after applying the changes and verify they were actually set. Also ensure that you are changing the UnitOfWork clone, not the original object.

  • Typecasting using Reflection

    Hi !
    How do I type cast classes using reflection?
    I use my own classloader and load a few classes, say 'myinterface', 'myinterfaceimpl' and 'someclass' in that custom classloader.
    'myinterface' class is public where as the implementation class, 'myinterfaceimpl', access is private. 'someclass' has a method whose return type is 'myinterface', and it returns an object of instance 'myinterfaceimpl' (which is an innerclass).
    1. My application starts with the system classpath (where the above 3 classes are not present).
    2. My classloader loads these 3 classes.
    3. Using reflection, I invoke the specified method in 'someclass', whose return type is 'myinterface'.
    4. Now I am unable to invoke a public method defined in the interface, since the implementation class level access is private. I get an IllegalAccessException, when I try to invoke a method in the object returned.
    5. I feel it would work, if I can somehow typecast the object returned from the method invocation to the interface class and then invoke the method.
    6. The same scenario works when I don't use reflection and have them in the classpath.
    Any help would be greatly appreciated. I saw a few postings related to this in the forum, but I am unable to find an answer.
    Best Regards,
    Ramesh.

    4. Now I am unable to invoke a public method defined
    in the interface, since the implementation class level
    access is private. I get an IllegalAccessException,
    when I try to invoke a method in the object returned.Private methods cannot be used to implement methods that the interface specifies to be public, as far as I know. A class that claimed to implement an interface that way should not compile.
    5. I feel it would work, if I can somehow typecast the
    object returned from the method invocation to the
    interface class and then invoke the method.
    6. The same scenario works when I don't use reflection
    and have them in the classpath.Perhaps the class you have doesn't claim to implement the interface, but just happens to have methods with the same signature, although some of them are private? If that's the case then you have a design problem that should not be worked around this way. Fix the class to implement the interface properly and you won't have to deal with any of this nonsense.

Maybe you are looking for

  • Self Registration in OIM 11g

    Hi, Can some one guide me on how to add User defined fields to self Registration page.My requirement is : In self registration form(at the login page),I have to add some UDFs and delete some existing fields. 2.User should be created immediately - no

  • Safari 7.0.1 not showing images

    Safari isn't showing images for certain websites. For instance, I'm trying to view a Big Cartel shop and the images won't load at all, even though the links are there. I checked in Firefox and Chrome, both work properly. Any suggestions?

  • Post-backup problems: missing files

    Hi guys! I just reinstalled OSX (but saved everything to the "Previous System" on my Mac HD), but many of my GB projects are missing files - where and how can I get them back? Thanks! Alec

  • How to modify criteria for critical tasks

    We want to make sure that if any task's slack is anything frm 0 to 4 days it should fall on the critical path. So that we can track all tasks which are meeting business process's rule criticality. Is there a way to do it;

  • UCCE SIP Dialer not active and PIM neither

    Dear Networkers, We have UCCE 8.5(4) installed. We have configured and installed aSIP dialer.  The issue is that the SIP dialer is not working and the PIM is not active. From the Dialer process output I can see the following after enabeling the EMSDi