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.

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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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();

  • Instantiating a class using new with implements or extends

    I have created a class as follows:
    class MyFileFilter extends javax.swing.filechooser.FileFilter implements java.io.FilenameFilter {     
         ...code here...
    }and it all works fine. If I try to use this code directly without importing the class, I would normally use the new keyword, but since this uses extends and implements, it is giving me errors such as:
    [javac] ';' expected
    Is there any way that I can use this with the new keyword, such as:
    MyFileFilter theFilter = new MyFileFilter extends javax.swing.filechooser.FileFilter implements java.io.FilenameFilter {
         ...code here...

    maybe your ';' error is really a coding error. Here is a sample of code where I do something similar in the middle of a method.
        public static void redirectOutput() {
            try {
                // make a print stream that logs the time for each entry.
                class TimeStampPrintStream
                    extends PrintStream {
                    public TimeStampPrintStream(OutputStream out, boolean b) {
                        super(out, b);
                    public void println(String s) {
                        super.println(new Date() + ": " + s);
                System.out.close();
                System.err.close();
                System.setErr(new TimeStampPrintStream(new FileOutputStream(com.perigee.fileio.LogFile.getLogDirectory() + "System.err"), true));
                System.setOut(new TimeStampPrintStream(new FileOutputStream(com.perigee.fileio.LogFile.getLogDirectory() + "System.out"), true));
                System.err.println("System.err File");
                    System.out.println("System.out File");
            } catch (Exception e) {
                System.out.println("Could not redirect System.out/err");
                e.printStackTrace();
        }

  • 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

  • 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.

  • Using reflection on passed classes

    Hello,
    I have been trying to write a common function to return the variables and values of a class passed into it. The function uses reflection to iterate through the Fields and returns a string of the variables and values. Is it anything to do with scope, as the same code works when I paste the method into the class I am looking at (See below)?
    I have pasted the code fragments below.
    Thanks
    stuart
    * Returns XML fragment of name value pairs of member/value
    * @param iClass the class under inspection
    * @return XML fragment of name value pairs of member/value
    public static String inspectMemberVariables(Class iClass)
    String oStr = new String();
    try
    Class c = iClass.getClass();
    Field[] f = c.getFields();
    System.out.println(f.length);
    for (int i=0; i < f.length; i++)
    // identify the field
    Field fld = c.getField( f.getName());
    //get the field name and grab the field value from the class
    oStr += f.getName()
    + "=\""
    + fld.get(c)
    + "\" ";
    } // for (int i=0; i < f.length; i++)
    oStr = "classname=\""
    + c.getName()
    + "\" "
    + oStr;
    } //end of try
    catch (NoSuchFieldException e)
    System.out.println(e);
    catch (SecurityException e)
    System.out.println(e);
    catch (IllegalAccessException e)
    System.out.println(e);
    } //end of catch
    return oStr;
    } // end ofinspectMemberVariables
    Where the code is called:
    public class ReflectionTest extends PPSpposEBCore
    public String strg;
    public ReflectionTest()
    String str2 = new String ();
    str2 = ClassProperties.inspectMemberVariables(this.getClass());
    System.out.println(str2);
    public static void main(String[] args)
    String str = new String ();
    try
    ReflectionTest rt = new ReflectionTest();
    // set dummy values to test
    rt.mPossessionId = 12;
    rt.mBusinessPossRef = "look it works";
    rt.mCreatedTs = new Date();
    //ClassProperties cp = new ClassProperties();
    //str2 = ClassProperties.inspectMemberVariables(rt.getClass());
    Class c = rt.getClass() ;
    Field[] f = c.getFields();
    System.out.println(f.length);
    for (int i=0; i < f.length; i++)
    // identify the field
    Field fld = c.getField( f.getName());
    //grab the field name and field value from the class
    str += f.getName()
    + "=\""
    + fld.get(rt)
    + "\" ";
    } // for (int i=0; i < f.length; i++)
    str = "classname=\""
    + c.getName()
    + "\" "
    + str;
    System.out.println(str);
    } //try
    catch (NoSuchFieldException e)
    System.out.println(e);
    catch (SecurityException e)
    System.out.println(e);
    catch (IllegalAccessException e)
    System.out.println(e);

    sorry it doesn't work, interface cannot have method body, i didn't know it. You couldn't access to private and protected datas with an exterior method. You can make a package with classes you want to inspect and a class who inspect. The classes of a package can access to protected datas.

  • How can i get all java class names from a package using reflection?

    hi,
    can i get all classes name from a package using reflection or any other way?
    If possible plz give the code with example.

    You can't, because the package doesn't have to be on the local machine. It could be ANYWHERE.
    For example, via a URLClassLoader (ie from the internet) I could load a class called:
    com.paperstack.NobodyExpectsTheSpanishInquisitionI haven't written it yet. But I might tomorrow. How are you going to determine if that class is in the package?
    This subject comes up a lot. If you want to do something a bit like what you're asking for (but not quite) there are plenty of threads on the subject. Use google and/or the forum search facility to find them.
    But the answer to your question, as you asked it, is "you can't do that".

  • Using Reflection can we find out details of inner classes in a class

    Hello All,
    Thanx in advance.
    I intend to figure out the name of the inner class and methods declared inside it. How can this be done using reflection API's.
    I need the above information to make an automated java doc creation tool for the project I am working in.
    Thanx again...
    VIkas

    Thanx silkm,
    Actually suggestion # 1 I have already tried. I used
    getClasses() method which returned me a Class[] of
    length = 0. i dunno Why?Because you are not using the reflection API correctly. If you read the javadocs you would know that it is structured so that all getXXX() methods return all XXX things that are public and are either declared by the target class or possibly inherited from superclasses.
    As contrasted to that, getDeclaredXXX() methods can return all XXX things (including private) but only declared by the target class (not inherited).
    You got an empty result back in your case most likely because all your nested/inner classes were non-public. Use getDeclaredClasses() instead.
    As to suggestion # 2, the exercise I am doing is a
    step before using the java doc tool. One has to insert
    a javadoc comment before the method begins in order to
    create a java doc. So thats it.This is independent of the reflection API but you might consider using the doclet API for this.

  • How to use reflection to get base classes protected field

    I have one base Base classes which have protected fields and public get method to get the field.
    class Base
    protected int proField;
    public int getProField(){return proField;}
    Class Derive extends base class Base
    class Derive extends Base implements OtherInterface
    public void funtion(){};
    Now I have an instance of Derive, how can I use reflection to get the protected field inherited from Base. It seems Java Reflection only give runtime accessibility to public field and decleared field, protected-inherited field is excluded.
    Thanks
    Lei

    as the last poster said, traverse up the class hierarchy.
    ex:
    private void doSumfinToField(String fieldName throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
    Class clazz = getClass();
    Field field = findFieldInClass(clazz, fieldName);
    //field.doSumfin;
    private Field findFieldInClass(Class clazz, String fieldName) throws NoSuchFieldException {
    try { // to find the field in this class    
    return clazz.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
    // if we don't have a superclass, continue
    if (clazz.getSuperclass().equals(Object.class)) {
    throw e;
    // check in the superclass
    return findFieldInClass(clazz.getSuperclass(), fieldName);
    }

  • Class A is Loading Class B Using Reflection

    Hi,
    I am facing the below problem.
    Class A is loading Class B By Using Reflection package.
    Class B is one jar (Eg: B.jar) ,Class A is one Jar (Eg: A.jar)
    Class B internally using Class A variables and methods. When ever loading the class B from Class A it is
    giving the exception is NoClassDefFoundError of Class A.
    We are loading the Class B from Class A only, Why Class A reference is not available in Class B
    Please help me on this
    Thanks
    T. Shankar Reddy

    ShankarReddyT wrote:
    Hi,
    I am facing the below problem.
    Class A is loading Class B By Using Reflection package.
    Class B is one jar (Eg: B.jar) ,Class A is one Jar (Eg: A.jar)
    Class B internally using Class A variables and methods. Myself I don't consider circular references a great idea.
    Presumably you are not using reflection solely because it is circular.
    When ever loading the class B from Class A it is
    giving the exception is NoClassDefFoundError of Class A.
    We are loading the Class B from Class A only, Why Class A reference is not available in Class B
    Several possibilities.
    1. Because you are attempting to load B in the static block of A. In that case the class A has not yet been loaded. And the VM will not try to reload A once it is in the process of loading. Which is pretty smart of the VM.
    2. Because there is a custom class loader involved.
    You might want to post the stack trace of the exception.

  • Creating a new instance of a member class?

    I'm writting a serialization library for a college project and I have a problem with deserializing an object which class contains a member class. A rough example:
    class Outer{
         class Member{
              double d =0;
         public Member member =new Member();     
    }Most basically I tried to get a new instance of the Member class in order to get the double field, change it's value, then use that new instance as a field of an object of the Outer class.
    Field f = Outer.class.getDeclaredField("member");
    f.setAccessible(true);
    f.getClass().newInstance(); Both this and the Constructor method throw an exception:
    Exception in thread "main" java.lang.InstantiationException: java.lang.reflect.Fieldpointing at the line with newInstance().
    Is there anything I can do to create an object of a member class? And if not then taking into account that I have to deserialize the Outer object from an XML file what could be the alternative?

    The error message already gives you a hint that it's not class Outer.Member you're instantiating there (review the API docs)...
    import java.lang.reflect.*;
    public class Outer{
      public static void main(final String[] args) {
        final Field f = Outer.class.getDeclaredField("member");
        f.setAccessible(true);
        final Constructor ctor =
                f.getType().getDeclaredConstructor(new Class[] { Outer.class });
        final Object outer = new Outer();
        final Object member = ctor.newInstance(new Object[] { outer });
        // set member.d
        f.set(outer, member);
      class Member{
        double d =0;
      public Member member =new Member();     
    }

  • Problem using reflection... Really urgent...

    Hi all,
    in my current program, i'm usin reflection a lot. This is due to the fact that i automatically generate some code, compile it, and run another program which uses the generated code.
    The generated code contains inner classes. For example:
    package mypackage;
    class A {
    public A() {}
    class B {
    public B() {}
    class C {
    public C() {}
    My question is: how can i instantiate, the classes B and C using reflection? i think i tried everything but when i run my prog i keep having error messages such as:
    - InstantiationException
    - NoSuchMethodException
    -etc...
    Any idea?
    Jack

    Consider this:
    Can you make the inner clases static? If you do, you may instatiate them by using names like A.B and A.B.C.
    If the inner classes are not made static, they need an instance of the enclosing class in order to be instantiated. This basically means that you may instantiate a B from inside a (non-static) method (or constructor) in A, and a C from within a method in B.
    One way of doing this is to create a method on A that creates a B (a factory method). Then, in order to get a B you first create an A, then call the factory method to get a B. By putting a factory method for C's in B, you could then go on to create a C from the B.
    But before going into this, you should consider whether you really need the inner classes to be non-static.

Maybe you are looking for

  • Create clob datatype in a column

    Hi, I am working in oracle9i and solaris 5.8. I want to create a table with a cloumn contains clob Datatype.. Please explain me how to create a clob datatype in a column and how to assign this and how to insert datas into the datatype... Regs..

  • Can't copy iPhoto from my backup disk

    I had to restore a lot of apps from my external backup drive yesterday. Most of them went OK, but, among others, iPhoto and iWeb wouldn't copy over to my iMac from the external drive. And, as luck would have it, I can't find my original iLife disks I

  • Cannot find "ant" in the oracle10g installation

    I have installed oracle10g application server. i was asked to please make sure that the ant command associated with the OC4J ant distribution is in your execution path (%OC4J_HOME%/ant/bin). the problem is 1. which directory in oracle10g does the oc4

  • Changing a Status without having write permission?

    Hi, is it possible to change a status without having write permission on the cFolders Dokument Object? It it is possible, how can i do that? Thanks!

  • Uninstalled and reinstalled the firefox, i can't get the bookmarks back

    I always use the sync to back up all my bookmarks and the others, but i noticed Firefox was playing up, so i uninstalled and then reinstalled it. the sync didn't work and i have lost all my bookmarks and the others. how can i get them back? Please i