Access enclosing Instance at runtime

I try to create a general Method to get a new Instance of a given Object:
class A {
     public B b = new B();
     public class B {
public class SpeedTest {
     public static Object getMeANew(Object o) {
          Class c = o.getClass();
          try {
               return c.newInstance();
          } catch (Exception e) {               
               e.printStackTrace();
          return null;          
     public static void main(String[] args) {               
          A a = new A();
          Object obj = getMeANew(a);  // this is just fine
          obj = getMeANew( ((A)obj).b); // runtime error
}I can't create an Instance of B at runtime.
I played with the new method and got this:
        public static Object getMeANew(Object o) {
          Class c = o.getClass();
          Class decl = c.getDeclaringClass();
          if (decl != null) {
               Constructor cons = null;               
               try {
                    cons = c.getConstructor(decl);
               } catch (Exception e) {               
                    e.printStackTrace();
               try {
                    return cons.newInstance(decl.newInstance());  // << problem
               } catch (Exception e) {               
                    e.printStackTrace();
          } else {          
               try {
                    return c.newInstance();
               } catch (Exception e) {               
                    e.printStackTrace();
          return null;          
     }But this is not a full solution consider this example:
class A {
     public int value;
     public B b = new B();
     public class B {
          public void print() {
               System.out.println(value);
        public static void main(String[] args) {               
          A a = new A();
          a.value = 100;
          a.b.print();  // << prints 100
          a.b = (A.B)getMeANew(a.b);
          a.b.print(); // << prints 0
     }I want that both print() result in '100' so i'am looking for something like:
cons.newInstance(o.getEnclosingInstance());   // << Something that don't require a new field in every ObjectIs this possible ?

Nobody has a solution?
What is the qualified name to access the enclosing class instance (i.e. the "this$0" member)?
Or, for the code snippet below, what is the qualified name for the getEnclosingClass() method?
public class Foo
    int i = 42 ;
    public class Bar { }
    public static Object getEnclosingClass(Object o)
     try { return o.getClass().getDeclaredField("this$0").get(o) ; }
     catch (NoSuchFieldException x) {}
     catch (IllegalAccessException x) {} ;
     return null ;
    public static void main(String[] args)
     Foo foo = new Foo() ;
     Bar bar = foo.new Bar() ;
     System.err.println(((Foo)getEnclosingClass(bar)).i) ;
}thx for assistance!

Similar Messages

  • Can not access the Instance Data of a Singleton class from MBean

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

  • How to get all property names and values of an bean instance at runtime?

    How can I get all property names and values of an bean instance at runtime?
    (The class of the bean instance is dynamic and I can not know before I write the code .)

    Look at Class. It has a way to get at all public methods and attributes.
    If you need to get to private attributes you can do what the Introspector does and expect the methods to follow the Bean pattern and pull the attributes out based upon that. Privates are all hidden from direct access but through the Bean Pattern they can be figured out.

  • How to create multiple component instances at runtime using java

    Hi,
    I need to create component instances at runtime using java.I found ComponentSet.add method.But I am not finding a way to get handle of ComponentSet.
    I see methods with params of IRuntimeNode.But how to get ComponentSet from IRuntimeNode.
    If anybody knows or have sampel code then please share with me.
    thanks,
    ashok

    Ashok --
    This is a common challenge for those using Configurator Extensions with multiple instantiation for the first time. The problem is that the CIO's representation of the structure for multiply-instantiable Components differs slightly from what both Configurator Developer users and Configurator Runtime users see in those respective applications. Multiply-instantiable Components are not direct children of the Model in which they're defined. Internally, there is an entity that sits between the parent Model and the instantiable Components; that intermediate entity is the ComponentSet object you've found in the CIO documentation.
    If the name of your multiply-instantiable Component is "My Component", then its ComponentSet may be accessed simply by calling getChildByName("My Component") on its parent Model; a List of the instantiated Components may be accessed with the ComponentSet's getChildComponentNodes() method, and instances may be added and deleted using its add() and delete() methods.
    Hope this helps.
    Eogan

  • Enclosing Instances When Subclassing Inner Classes

    Hi,
    I need to subclass an inner class but when I write code for its constructor I get the error "an enclosing instance that contains at.MainHandler.innerClass is required".
    at.MainHandler is my outer class and my new class looks something like this:
    public class newClass extends at.MainHandler.innerClass {
         //Constructor
         public newClass (int a, int b) {
             super( a );
        }//Constructor
    }//ClassI understand that the inner class to which 'super' refers must somehow be bound to its outer class(at.MainHandler) if I want newClass to access the outer class methods, but what is the correct syntax needed to achieve this?
    I've looked at other posts on similar topics but am still unable to grasp precisely what is needed.
    Sid

    These are some working examples:
    class A {
         class InA {}
    class B extends A {
         class InB extends InA {}
    class A {
         static class InA {}
    class InB extends A.InA {}
    class A {
         class InA {}
    class InB extends A.InA {
         InB(A a) {
              a.super();
    }

  • No enclosing instance of type Foo is accessible

    i m trying to access class within a class it is giving this error
    No enclosing instance of type Foo is accessible. Must qualify the allocation with an enclosing instance of type Foo (e.g. x.new A() where x is an instance of Foo).what does this mean and i can make it correct...??

    my class file is
    public class a{
       public class b{
       public class c{
    }and jsp page where i want to access class b
    a.b initialize = new a.b();in my jsp page it is giving error :
    No enclosing instance of type LanguageTranslate is accessible. Must qualify the allocation with an
    enclosing instance of type LanguageTranslate (e.g. x.new A() where x is an instance of
    LanguageTranslate).

  • Enclosing instance

    I've never seen this error before. I was trying to create a instance of an inner-class. The code is declared like this:
    static ShuttleController shuttleControl;Then it is created in the main Method like this:
    shuttleControl = new ShuttleController();I'm using eclipse to program this code and it gave me this error:
    No enclosing instance of type SpacePanel is accessible. Must qualify the allocation with an enclosing instance of type SpacePanel (e.g. x.new A() where x is an instance of SpacePanel).This is the code for the class ShuttleControlle:
    class ShuttleController implements Runnable
              public ShuttleController()
              public void run()
                   shuttle.update(WIDTH/2, HEIGHT/2, rotation);
                   xPos += xMom;
                   yPos += yMom;
         }This class is an inner-class in the class SpacePanel

    Objects of an "inner class" can access the instance of the enclosing class and its fields; therefore, they must have an implicit reference to the enclosing object, and cannot be instantiated in static context.
    Maybe you are looking for a "nested class" instead, which does not have a reference to the enclosing object. To do that, you add the "static" keyword:
    static class ShuttleController implements RunnableEdited by: spoon_ on Dec 15, 2007 10:21 PM

  • Accessing internal tables at runtime.

    Hi all,
    I am writing a code where in i have to transfer data from excel to database table.
    Iam getting the excel data in an itab. Can anybody help me with how to access internal tables at runtime ?
    i am using the following code with sy-tabix. here, when the sy-tabix is odd it picks up the value,
    but i want that within the same loop when i increment sy-tabix by 1, then it should fetch the second column of same row. But its not working as it shows an error that it does not permit subfield access.
    the code is as follows:
    LOOP AT t_tab[] into wa_tab .
      data: l_tabix type sy-tabix,
            name_index type sy-tabix.
            data: c type i.
            l_tabix = sy-tabix.
            name_index = l_tabix+1.
            c = ( l_tabix mod 2 ).
    ******to check if sy-tabix is odd**********
           if c ne 0.
             READ TABLE t_tab into wa_tab index l_tabix.
             wa_product1-product = wa_tab-VALUE.
    ************incrementing sy-tabix*************
             READ TABLE t_tab into wa_tab index name_index. (here it shows error)
             wa_product1-product_name = wa_tab-value.
           endif.
      endloop.
    Thanks in advance.

    Hi Omer,
    Copy and paste this code.
    =====================================
    REPORT ztest_create_data_dynamic .
    TYPE-POOLS: slis.
    DATA: it_fcat TYPE slis_t_fieldcat_alv,
    is_fcat LIKE LINE OF it_fcat.
    DATA: it_fieldcat TYPE lvc_t_fcat,
    is_fieldcat LIKE LINE OF it_fieldcat.
    DATA: new_table TYPE REF TO data.
    DATA: new_line TYPE REF TO data.
    FIELD-SYMBOLS: <l_table> TYPE ANY TABLE,
    <l_line> TYPE ANY,
    <l_field> TYPE ANY.
    Build fieldcat
    CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
    i_structure_name = 'SYST'
    CHANGING
    ct_fieldcat = it_fcat[].
    LOOP AT it_fcat INTO is_fcat WHERE NOT reptext_ddic IS initial.
    MOVE-CORRESPONDING is_fcat TO is_fieldcat.
    is_fieldcat-fieldname = is_fcat-fieldname.
    is_fieldcat-ref_field = is_fcat-fieldname.
    is_fieldcat-ref_table = is_fcat-ref_tabname.
    APPEND is_fieldcat TO it_fieldcat.
    ENDLOOP.
    Create a new Table
    CALL METHOD cl_alv_table_create=>create_dynamic_table
    EXPORTING
    it_fieldcatalog = it_fieldcat
    IMPORTING
    ep_table = new_table.
    Create a new Line with the same structure of the table.
    ASSIGN new_table->* TO <l_table>.
    CREATE DATA new_line LIKE LINE OF <l_table>.
    ASSIGN new_line->* TO <l_line>.
    Test it...
    DO 30 TIMES.
    ASSIGN COMPONENT 'SUBRC' OF STRUCTURE <l_line> TO <l_field>.
    <l_field> = sy-index.
    INSERT <l_line> INTO TABLE <l_table>.
    ENDDO.
    LOOP AT <l_table> ASSIGNING <l_line>.
    ASSIGN COMPONENT 'SUBRC' OF STRUCTURE <l_line> TO <l_field>.
    WRITE <l_field>.
    ENDLOOP.

  • How do I create a certain amount of instances at runtime?

    If i want a certain amount of instances at runtime, how can i do it?
    say, if i write a program that read an input from a keyboard and create a certain amount of instances. or read an input from a keyboard to be an instance variable. Can i do it? How? Please help!

    If i want a certain amount of instances at runtime,
    how can i do it?
    say, if i write a program that read an input from a
    keyboard and create a certain amount of instances.
    or read an input from a keyboard to be an instance
    variable. Can i do it? How? Please help!How much instance do you want? 1 gm? 10 gms? 1 pound? a kilo?

  • Reference to enclosing instance in inner class constructor

    Is there any Java compiler which assigns reference to enclosing instance in constructor of inner clase before invoking super class constructor?
    class Outer {
    class Inner extends Global {
    public Inner(int x) {
    // I want (Outer.this != null) here
    super();
    class Global {
    public Global(int x) {

    class Outer {
    class Inner extends Global {
    public Inner(int x) {
    // I want (Outer.this != null) hereOuter.this is never null at this point. A non-static
    inner class always has an implicit reference to an
    instance of the enclosing class.Try this:
    class Outer {
    int m;
    class Inner extends Global {
    public Inner(int x) {
    super(x);
    protected void init(int x) {
    xxx = Outer.this.m + x; // Null pointer exception!!!
    class Global {
    int xxx;
    public Global(int x) {
    init(x);
    protected void init(int x) {
    xxx = x;

  • How to refer to enclosing instance from within the member class?

    Hi
    How to refer to the enclosing instance from within the member class?
    I have the following code :
    import java.awt.*;
    import java.awt.event.*;
    public class MyDialog extends Dialog
         public MyDialog(Frame fr,boolean modal)
              super(fr,modal);
              addWindowListener(new MyWindowAdapter());
         public void paint(Graphics g)
              g.drawString("Modal Dialogs are sometimes needed...",10,10);
         class MyWindowAdapter extends WindowAdapter
              public void windowClosing(WindowEvent evt)
                   //MyDialog.close(); // is this right?
    In the above code, how can I call the "close()" method of the "Dialog" class (which is the enclosing class) from the inner class?
    Thanks in advance.
    Senthil.

    Hi Senthil,
    You can directly call the outer class method. Otherwise use the following way MyDialog.this.close(); (But there is no close() method in Dialog!!)
    If this is not you expected, give me more details about problem.
    (Siva E.)

  • Need to change the name of a GP process instance at runtime.

    Is there a way to change the name of a GP process instance at runtime?  I would like to change the name of the process instance to include the employee's name who initiated the process.  This way when the process owner or overseer displays thier list of processes from the GP Runtime Work Center, they can tell who initiated each process.
    Does anyone know how to do this?

    Hi Karen,
    If the users are invoking the Process from Web Dynpro or some other application using GP API, then you can try the followigI.
    You can try using the startProcess() method of the IGPRuntimeManager object. It has multiple paramaters of which two(second and third) are for the userProvidedName and userProvidedDescription. You can set any name and description while invoking the GP process and the name and description should appear in the Runtime for the owners/overseers/administrators in hte list of process instances. You can add the name of the Employee while setting that name and description.
    help.sap.com link for the info on this:
    http://help.sap.com/saphelp_nw70/helpdata/en/43/fcdf77fc6510b3e10000000a11466f/frameset.htm
    Regards,
    Ajay

  • Error: cannot access directory oracle\jsp\runtime

    I got this error when try to add a existing project to JDeveloper 9.0.3.4
    Error: cannot access directory oracle\jsp\runtime; verify that directory is reachable from classpath and/or sourcepath
    can someone help me?
    thanks

    Xinwei -
    Make sure you have added the correct libraries to your project; adding JSP Runtime to your project should alleviate this error.
    Hope this helps,
    Lynn
    Java Tools Team

  • Error: cannot access class oracle.jsp.runtime.HttpJsp; file oracle\jsp\runtime\HttpJs

    Hello,
    where is now oracle\jsp\runtime\HttpJsp.class located?
    thanks.
    Oleg.

    Same problem,
    Error: cannot access class oracle.jsp.runtime.HttpJsp; file oracle\jsp\runtime\HttpJsp.class not found
    Thanks
    aldo

  • Cannot access Oracle instances

    Hi,
    I'm hoping I can get some help. I am currently trying to access an Oracle instance, however whenever I try to access the instance via Oracle appliactions (enterprise manager, SQLPLUS) or a third party application, the application just hangs. I get no error message returned whatsoever. I have also tried connecting to a 'non-existant' schema and I get back the message 'TNS could not resolve service name' which i would expect. Any help would be much appreciated.

    Hi
    sqlnet.ora and tnsnames.ora look ok.
    Used tnsping on the service and it has returned:
    Used TNSNAMES adapter to resolve the alias
    Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)
    (HOST = cvge561a)(PORT = 1521))) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_N
    AME = GEOSTORE)))
    and from there it just hangs
    I have tried the NET configuration wizard and go through the steps of editing the current listener. I have selected NO to configure another listener and then the application just hangs again.
    This is all that is returned from trying to run sqlplus in the command prompt
    SQL*Plus: Release 9.2.0.6.0 - Production on Thu Jan 10 14:16:52 2008
    Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
    From here, it does not connect to the DB, neither does it give an error message. However, if you put in the incorrect values, it will return:
    SQL*Plus: Release 9.2.0.6.0 - Production on Thu Jan 10 14:19:20 2008
    Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
    ERROR:
    ORA-12154: TNS:could not resolve service name
    as expected.

Maybe you are looking for

  • My iphone 4s will no longer connect to any wifi

    It's been about 2, maybe 3 weeks since it's been able to connect, and stay connected to ANY wifi. It started out as not being able to find my connection at home unless I did a hard reset on my phone, and has since escalated to not finding any wifi an

  • Is it ok to make changes to import map by loading files from port manually?

    Hi all, I want to load the files from the port which is set to manual and then want to create/modify existing maps already assigned to ports.Is it ok to do this way or do we need to create the import maps with all mappings manually other than port op

  • Can I to use a remote agent in CCX??

    Hi, I have a site A (Brazil) with CUCM and CCX working... But, I need to create another queue with a new agent that will stay at Chile (Site B)... Can I to register the new agent at Brazil CUCM? Can I to create a new queue at Brazil CCX for him? What

  • KANBAN with WM

    Hi, I am getting Error Message while doing GR for inbound delivery through VL06I for KANBAN receipts Message no.PK366 You are posting a goods receipt that sets several Kanbans to the status Full. At the same time, the material is being posted to stor

  • Hash Function used by oracle

    Hi, I am working on partition tables. I want to know more abt how hash partitioning works. I want to know the exact hash function used by oracle. I searched a lot, but couldn't find an exact answer on the net. Plz assist. Thanks in advance. Subha