Anonymous class - reference to enclosing object

Hi,
I have a class (which is in fact an Adapter that implements several interfaces
for EventListener) that should be instantiated in the code via an anonymous
class, i.e. like this
this.addAdapter( new Adapter() {
// implemented methods here
Now I have the problem that when I pass the instance of the anonymous class
later to a method somewhere else, I need a reference to the object which
instantiated it:
public class AClass {
priavte BClass bClass;
private Adapter adapter;
public AClass() {
this.addAdapter( new Adapter() {
// implemented methods here
bClass = new BcLass();
bClass.doSomething
void addAdpater( Adpater ad ) {
this.adpater = ad;
public class BClass {
public BClass() {
doSomething( Adapter ad ) {
// how can I get a reference to the instance
// of AClass that called this method ?????
My IDE shows the needed object as member this$0 of the Adpater, so I
suppose there is some way to get at the reference to this enclosing
object, but how???
Thanks in advance for any idea,
Leif

If it's possible to get the reference without the adapter explicitly giving it to you, then everything that's been written about read-only adapters is silly, so I would bet that it's not possible.
Your adapter is written as an inner class, so it has access to all the enclosing object's state. If you can modify the adapter class, you could expose as much of that state as you wanted. Maybe that's as good as the reference for your purposes.
But maybe not. So the only option I could see is that the adapter itself has a method
public AClass getEnclosingAClassInstance()
which returns a reference to the enclosing class. The way to set it might be to make a corresponding set method which AClass calls with 'this' before handing off the adapter to BClass, or by AClass itself providing a getThis method, which the adapter could call. I'm pretty sure you can't get anymore direct access to the enclosing 'this', because the adapter's 'this' shadows it.
All of which leaves me wondering--why? It's so weird and un-adapter-like that I suspect it's the wrong idiom. But maybe you know something I don't....

Similar Messages

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

  • Anonymous class explanation?

    Ok, so the following piece of code compiles and run fine printing 1  2 3. My problem is that I cant understand it thoroughly... So, obj is a reference varialbe of type object that refers to an array object...so far I think I am right... but after the " ; " I have another curly brace opening... Is that an anonymous class? Is that also referenced by " obj " ? When that curly brace closes, a " ; " seems to be optional making no difference.....Any explanations welcome. Thanks.
    public class Test { 
        public static void main(String[] args) {
            Object obj = new int[]{1,2,3};{
                int[] someArray = (int[])obj;
                for (int I:someArray)
                    System.out.print(I+"");
            }  // Wether a " ; " is placed right after this brace doesnt seem to matter
    }

    What you defined is a block:
    http://java.sun.com/docs/books/jls/third_edition/html/
    statements.html#14.2
    I'm trying to think, but I can't remember ever seeing
    someone introduce
    a block just for the heck of it, versus it being the
    body of a loop, for example.
    Congratulations ;-)as usual, I've seen it in our codebase, Doctor :-(
    I need a new job

  • How to use application class reference in the controller methods of BSP

    Hi,
    I have created a bsp application and also created an application class and assigned it to the application class. In the application class, I have created attribute TEXT type string(public and instance parameter).
    In the controller let's say main.do, I am trying to give a value to to the text by adding the following code.
    application->text = 'test'.
    I am getting syntax error saying field 'text' is unknown. It is not contained in one of the specified tables nor defined by DATA statement. 
    Please can someone let me know how to use the application class in the coding with an example. I couldn't find how exactly this has to be reference. Please help.
    Best regards
    Siva

    Hi,
    if you are having main controller and sub-controller then you may need to use below coding to use application class reference.
    *Data declaration
      DATA:  obj_cntrl        TYPE REF TO cl_bsp_controller2,
             obj_sub_cntrl   TYPE REF TO z_cl_sub_cntl,
             application TYPE REF TO z_cl_application.
    *Get the controller
      CALL METHOD obj_main_cntrl->get_controller   "obj_main_cntrl is the object of main controller
        EXPORTING
          controller_id       = 'SUB'   "Controller ID
        RECEIVING
          controller_instance = obj_cntrl  .
      obj_sub_cntrl ?= obj_cntrl  .
      application ?= obj_sub_cntrl ->application.
    or simply use below code in your controller method.
      application ?= me->application.
    Thnaks,
    Chandra

  • Reference to an object by String(ID)?

    I am trying to build a glow container/manager in order to
    turn off and turn on appropriate component. In fact, when a
    specific component respond to a click, it will be glowed. But if
    the user click on another specific component, the previous glowed
    should unglow and the new one will be glowed.
    Now, to do this, I created a class with 2 elements:
    objReference:String and glowActive:Boolean. I also created an
    ArrayCollection of all the component that can respond to the glow
    effect and put them inside like this:
    objReference = [object].ID
    And every component get FALSE for glowActive at the
    initiation of the ArrayCollection.
    I have a problem with the recognization of the object ID.
    When I tried to play the glow using the objReference, the system
    indicate the following error:
    TypeError: Error #1006: value is not a function.
    at
    mx.effects::EffectInstance/play()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\effec ts\EffectInstance.as:584]
    at
    mx.effects.effectClasses::GlowInstance/play()[E:\dev\3.0.x\frameworks\projects\framework\ src\mx\effects\effectClasses\GlowInstance.as:194]
    at
    mx.effects::EffectInstance/startEffect()[E:\dev\3.0.x\frameworks\projects\framework\src\m x\effects\EffectInstance.as:569]
    at
    mx.effects::Effect/play()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\effects\Effec t.as:930]
    at accueil/setCategoryGlowIn()[C:\Documents and Settings\DJ
    FYB\My
    Documents\CharlesValcourt\includes\charlesvalcourt_logique.as:303]
    at accueil/clickCategoryBox()[C:\Documents and Settings\DJ
    FYB\My
    Documents\CharlesValcourt\includes\charlesvalcourt_logique.as:282]
    I am a bit confuse on how to call an object by reference and
    stored the referene of the object in somewhere else (in my case, in
    a ArrayCollection).

    Youpi!!! I found how to made it!!!
    First, I finally have to make the property objReference in my
    class GlowObjectReferencer as an Object in order to work.
    Than, I have to pass myHB as the Object (which, if I
    understand properly, will put a reference of the current Object
    into the new class Object).
    var _objReference:GlowObjectReferencer = new
    GlowObjectReferencer (myHB, false);
    And when I run my functions to manage the Glow FX
    (setAllCategoryGlowOut and setCategoryGlowIn), it is now working
    fine!!!
    I am so happy now! I knew it was possible but in my mind, it
    was just not logic to store an Object in the class but it seems
    that it is what I need to do! But just to make sure: what I pass to
    the class GlowObjectReferencer as the first property is only the
    reference to myHB? Not a copy of myHB; right?
    Again, thank Tracy because you force me to find the way to do
    it!!! ;-))

  • Where is the anonymous class in this? (lotsa code)

    When I compile ThreadPool.java, I get three classes: ThreadPool.class, ThreadPool$WorkerThread.class, and ThreadPool$1.class. I understand the first two, but I can't figure out where the anonymous class is coming from. Could it be some kind of automatically-generated wrapper class caused by the fact that all accesses to the Queue object are within synchronized blocks? Curiosity attacks!
    Thanks,
    Krum
    ThreadPool.java:
    package krum.util;
    * A thread pool with a bounded task queue and fixed number of worker threads.
    public class ThreadPool {
       protected Queue queue;
    public ThreadPool(int threads, int taskQueueSize) {
       queue = new Queue(taskQueueSize);
       /* create the worker threads */
       for(int i = 0; i < threads; ++i) {
          Thread t = new Thread(new WorkerThread());
          t.setDaemon(true);
          t.start();
    * Queues a task to be executed by this ThreadPool.  If the task queue is
    * full, the task will run in the calling thread.  (Could easily be modified
    * to throw an exception instead.)
    public void doTask(Runnable task) {
       boolean added = false;
       synchronized(queue) {
          if(!queue.isFull()) {
             queue.add(task);
             added = true;
             queue.notify();
       if(!added) task.run();
    * Tests if the task queue is empty.  Useful if you want to wait for all
    * queued tasks to complete before terminating your program.
    public boolean queueEmpty() {
       synchronized(queue) {
          return queue.isEmpty();
    private class WorkerThread implements Runnable {
    public void run() {
       Runnable task;
       while(true) {
          task = null;
          synchronized(queue) {
             try {
                if(queue.isEmpty()) queue.wait();
                else task = (Runnable)queue.getNext();
             } catch(InterruptedException e) { break; }
          if(task != null) task.run();
    } /* end inner class WorkerThread */
    } /* end class ThreadPool */Queue.java:
    package krum.util;
    * Implements a FIFO queue for storage and retrieval of objects.  This class
    * is not synchronized.
    public class Queue {
         /** circular buffer containing queued objects */
         protected Object[] queue;
         /** index of next object to be returned */
         protected int nextReturn;
         /** index in which to store next object inserted */
         protected int nextInsert;
    public Queue(int capacity) {
         queue = new Object[capacity];
         nextInsert = 0;
         nextReturn = 0;
    public boolean isEmpty() { return(queue[nextReturn] == null); }
    public boolean isFull() { return(queue[nextInsert] != null); }
    public void add(Object obj) throws QueueException {
         if(queue[nextInsert] == null) {
              queue[nextInsert] = obj;
              ++nextInsert;
              nextInsert %= queue.length;
         } else throw new QueueException();
    public Object getNext() throws QueueException {
         if(queue[nextReturn] != null) {
              Object obj = queue[nextReturn];
              queue[nextReturn] = null;
              ++nextReturn;
              nextReturn %= queue.length;
              return obj;
         } else throw new QueueException();
    } /* end class Queue */QueueException.java:
    package krum.util;
    public class QueueException extends RuntimeException { }

    I can't explain why it happens, but I've seen this
    behaviour before. I found that it was to do with an
    inner class (WorkerThread in your code) having a
    private constructor - if I made my inner class
    constructor at least package (default) access, then
    the anonymous class was no longer created.
    The generated default constructor for a class has the
    same access modifier as the class, so in your example,
    the default constructor that the compiler generates is
    private.
    I suspect the problem will go away if you either:
    1. Remove the private modifier from the WorkerThread
    class declaration.
    or:
    2. Add a no-args constructor to the WorkerThread
    class, and don't specify an access modifier.Yes, the reason is the private constructor. After decompile using JAD, the reason seems to be: if a private inner class does not explicitly have any constructor, a default no-arguments private constructor is created, and seems this default constructor can't be accessed directly (in source code, it can). So, another no-private constructor (package accessible) is created automatically (with an argument of Object's type), and the
    new WorkThread();is actually like this:
    new WorkThread(null);
    private class WorkThread implements Runnable{
       private WorkThread(){}
       WorkThread(Object obj) {
          this();
    }and I would guess it's using anonymous class tech to achieve this like:
    new WorkThread(null) {
       WorkThread(Object obj){
          this();
    }The JLS should have specified this situation.

  • Bug? Unable to add ActionListener using Anonymous class.

    Hi,
    I come accross one strange behaviour while adding ActionListener to RCF component.
    I am trying to add the ActionListener in the managed bean using the Anonymous.
    We can add the actionListener to a button using following methods. I am talking about the the first case. Only this case is not working. Rest other 2 cases are working properly.
    Case 1:
    class MyClass {
         RichCommmandButton btnTest = new RichCommmandButton();
         public MyClass(){
              btnTest.addActionListener(new ActionListener(){
                   public void processAction(ActionEvent event){
    Case 2:
    class MyClass implements ActionListener {
         RichCommmandButton btnTest = new RichCommmandButton();
         public void processAction(ActionEvent event){
    <af:button binding="#{myClassBean.btnTest}" actionListener="#{myClassBean.processAction}"/>
    Case 3:
    class MyClass implements ActionListener {
         RichCommmandButton btnTest = new RichCommmandButton();
         public void addActionLister(){
              //Use EL to add processAction(). Create MethodBinding
              FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory exprfactory = facesContext.getApplication().getExpressionFactory();
              MethodExpression actionListener =
    exprfactory.createMethodExpression(elContext, "#{myClassBean.processAction}", null, new Class[] { ActionEvent.class });
              btnTest.setActionListener(actionListener);
         public void processAction(ActionEvent event){
    Java has provided good way to use the Anonymous classes while adding the listeners. It should work with the RCF also.
    Some how i found the case 1 usefull, as i can have as many buttons in my screen and i can add the actionListener in one method. Also it is easy to read. I dont have to see the JSPX page to find the associated actionListener method.
    Is it a bug or i am wrong at some point?
    Any sujjestions are welcome.
    - Sujay.

    Hello Sujay,
    As I said in my previous reply, you can try with request scope. In JSF you shouldn't use the binding attribute very often. I agree that anonymous class is nice, but don't forget that you might be dealing with client state saving here so it cannot be perfectly compared with Swing that maintains everything in RAM. What I think happens with you currently is the following:
    1. Bean is created and the button instance as well. The ActionListener is added to the button;
    2. The view is rendered and while it is, the binding attribute is evaluated, resulting in the get method of your bean being called;
    3. Since the method returns something different than null, the button instance created in 1. get used in the component tree;
    4. The tree's state is saved on the client, since your class isn't a StateHolder, nor Serializable, the StateManager doesn't know how to deal with it so it gets discarded from the saved state and maybe from the component itself (would have to debug the render view phase to be sure);
    5. The postback request arrives, the tree is restored. When the handler reaches the button, it call the bean that returns the same instance that was used in the previous tree (since not request scoped), which is BAD because the remaining of the tree is not made of the same object instances, but rather new deserialized ones. The component then gets updated from the client state saved in 4, this might also be where the listener get removed (again debugging would tell you this, but I would tend more with the previous possibility). Note that with a request scoped bean you would have to add the listener during the first get method call (by checking if the component is null) or in the constructor as you're doing right now. It would be a very clean way and you could give the request bean (and thus the listener) access to the conversation scoped bean through injection which is very nice as well.
    6. The invoke application phase occurs and the listener is no longer there.
    Btw, this isn't a rich client issue, more a specification one. I'm curious if it works in a simple JSF RI application, if it does then I guess it would be a bug in Trinidad and/or rich client state handling architecture (using FacesBean).
    Regards,
    ~ Simon

  • Getting references to the objects in a VM to dynamically link MBeans

    Hi, I am dynamically generating MBeans and using Apache BCEL to change the resource classes to link themselves to the MBeans. The objective is to instrument applications wich we can't access the code and, if possible, do it on a running one.
    I could use the Instrumentation API to change the classes of the application and the Attach API to do it on a running application, but only new instances would be affected, so the previously created objects would not be managed. I can generate MBeans in many ways, but can't link them to already running application objects.
    So, what i want to know is in the title: is there a way to get references to the objects actually loaded in a Virtual Machine or another way to link an MBean to a running object?
    I saw McManus talk at Sun One 2006 about the different ways to link MBeans to application objects, but all of them look to need code changes or previous suport to dependency injection, for example.
    http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-3523.html
    I need it to a technical writing, so an official word can be enough, or even more helpful than a solution.
    Thanks,
    Gustavo

    Gustavo,
    Assuming I understand your question correctly, the only way I can see that you can enumerate instances of objects in a Java VM without changing the classes of those objects in any way is to use JVMTI <http://java.sun.com/javase/6/docs/platform/jvmti/jvmti.html#Heap_1_0>. That requires you to write native code somewhere as part of your solution. It is applicable to already-running apps via attach-on-demand <http://java.sun.com/javase/6/docs/jdk/api/attach/spec/index.html>. The MLet service from the JMX API might be convenient here to bridge from the jar file that the Attach API expects to the native code that you need to access JVMTI.
    As you can see this is pretty advanced stuff, but your ideas are interesting and I'd be interested in knowing how they work out.
    Regards,
    �amonn McManus -- JMX Spec Lead -- http://weblogs.java.net/blog/emcmanus

  • Link between classes: Reference Error

    Hi,
    I am still trying to create a movie clip array to make a list of objects appear on stage and have the user interact with them.
    This will be my game loop class called "LetterArray()".
    My main class is called "BugGoopFSGame()".
    After I add the line of code below into my LetterArray(). as class file I get the error message below:
    Code entered:
    private var  lettersL1:Array = new Array[a,f,g,h,i,n,o,s,t];
    This is the error message I get:
    ReferenceError: Error #1069: Property [object T] not found on S and there is no default value.
        at LetterArray()
        at BugGoopFSGame()
    I am sure the reference I use between the two files are not good. Can you please tell me what code I should add and where.
    Thanks for your help!
    Charine
    This is the code in my main class - BugGoopFSGame()
    package
        import flash.display.*;
        import flash.utils.Timer;
        import flash.events.*;
        import flash.events.MouseEvent;
        import flash.media.Sound;
        import flash.events.Event;
        import flash.media.SoundChannel;
        import flash.media.SoundMixer;
        import flash.media.SoundTransform;
        import flash.text.*;
        import flash.net.URLRequest;
        public class BugGoopFSGame extends MovieClip
            public var mybackground:BackGround;
            public var letterArray:LetterArray = new LetterArray(stage); //this is how I link from main to gameloop
    This is the coce in my gameloop class - LetterArray()
    package
        import flash.display.*;
        import flash.events.*;
        import flash.text.*;
        import flash.utils.Timer;
        import flash.media.Sound;
        import flash.media.SoundChannel;
        import flash.net.URLRequest;
        public class LetterArray extends MovieClip
            private var _stage:Stage; //this reference works well to the main file. Should I somehow link it to the errorous code below?
            /*Movie clips that need to go into an array    */
            //level 1
            public var a:A = new A();
            public var f:F = new F();
            public var g:G = new G();
            public var h:H = new H();
            public var i:I = new I();
            public var n:N = new N();
            public var o:O = new O();
            public var s:S = new S();
            public var t:T = new T();
            private var letterArray:Array;
            private var  lettersL1:Array = new Array[a,f,g,h,i,n,o,s,t]; //this is the line that causes the error. I am sure it is because I need to add something to the main class.

    if, for example, A is a class name, you should use "A" and then use getDefinitionByName() to retrieve the class reference from the string.
    private var  lettersL1:Array = new Array['A','F','G','H','I','N','O','S','T'];
    for(var i:int=0;i<lettersL1.length;i++){
    var C:Class=Class(getDefinitionByName(lettersL1[i]));  // import flash.utils.getDefinitionByName
    var c:*=new C(); // create instances from the classes in lettersL1
    // do whatever with c
    or, move those instanciation statements into your LetterArray constructor or somewhere beyond like:
    package
        import flash.display.*;
        import flash.events.*;
        import flash.text.*;
        import flash.utils.Timer;
        import flash.media.Sound;
        import flash.media.SoundChannel;
        import flash.net.URLRequest;
        public class LetterArray extends MovieClip
            private var _stage:Stage; //this reference works well to the main file. Should I somehow link it to the errorous code below?
            private var letterArray:Array;
            private var  lettersL1:Array; //this is the line that causes the error. I am sure it is because I need to add something to the main class.
            public function LetterArray(ss:Stage):void{
                var a:A = new A();
                var f:F = new F();
                 etc
                lettersL1 = [a,f,...]
                _stage = ss;

  • Resolved reference placed in object with no cache

    Hi ,
    I have been seeing this error in my weblogic logs.The workflows are
    running fine and doing intended work. Have a look at the error message
    WARNING: Resolved reference placed in object with no cache.
    java.lang.Exception: printStackTrace
            at com.waveset.util.Util.printStackTrace(Util.java:6259)
            at com.waveset.object.PersistentObject.cacheWarning(PersistentObject.java:476)
            at com.waveset.object.PersistentObject.checkReference(PersistentObject.java:2683)
            at com.waveset.object.PersistentObject.checkReferences(PersistentObject.java:2718)
            at com.waveset.object.PersistentObject.addMemberObjectGroup(PersistentObject.java:1513)
            at com.waveset.workflow.WorkflowEngine.buildWorkItem(WorkflowEngine.java:4406)
            at com.waveset.workflow.WorkflowEngine.callManualAction(WorkflowEngine.java:4284)
            at com.waveset.workflow.WorkflowEngine.callAction(WorkflowEngine.java:3811)
            at com.waveset.workflow.WorkflowEngine.callAction(WorkflowEngine.java:3229)
            at com.waveset.workflow.WorkflowEngine.execute(WorkflowEngine.java:3070)
            at com.waveset.workflow.WorkflowEngine.makeTransition(WorkflowEngine.java:2809)
            at com.waveset.workflow.WorkflowEngine.checkExplicitTransitions(WorkflowEngine.java:2700)
            at com.waveset.workflow.WorkflowEngine.checkTransitions(WorkflowEngine.java:2486)
            at com.waveset.workflow.WorkflowEngine.processSteps(WorkflowEngine.java:1891)
            at com.waveset.workflow.WorkflowEngine.walkCases(WorkflowEngine.java:1748)
            at com.waveset.workflow.WorkflowEngine.walkCases(WorkflowEngine.java:1656)
            at com.waveset.workflow.WorkflowEngine.execute(WorkflowEngine.java:816)
            at com.waveset.workflow.WorkflowEngine.execute(WorkflowEngine.java:478)
            at com.waveset.workflow.WorkflowExecutor.execute(WorkflowExecutor.java:235)
            at com.waveset.task.Scheduler.execute(Scheduler.java:2393)
            at com.waveset.task.Scheduler.executeTask(Scheduler.java:2295)
            at com.waveset.task.TaskManager.executeTask(TaskManager.java:277)
            at com.waveset.workflow.Workflow.checkinWorkItem(Workflow.java:378)Any Ideas,
    Thanks

    Did anybody resolve this issue?
    I am getting com.waveset.util.WavesetException:Class com.omd.session.WorkflowServices not found.
    It seems the workflow status shows finished, but did not start the acctual workflow process of approvals and emails to the appropriate user accounts.
    Anybody has any clues about this exception?
    G

  • Vector clone references the same objects??

    Hi all
    I'm developing a simple chess program.
    Obviously, each move the user tries must be checked against the following sets of chess rules:
    1.) Whether it is that colour player's turn to move
    2.) Whether this move is valid for this specific piece (eg. 3 forward for a King --> invalid of course)
    3.) Whether this move will jeopardize the player's king (put it in check)
    If from any of the above the move is found to be invalid, the move is not executed.
    My program structure is briefly this:
    A. abstract super class 'ChessPiece' - subclassed by the various specific Chess Piece classes.
    Each of the specific ChessPiece subclasses must implement an abstract method to check if a
    proposed move is valid, and also a method to actually do the move...
    B. 'PieceManager' class - has a Vector of ChessPieces:
    This class checks whether the given move is valid:
    For the piece: by calling the checking method (see A above)
    For the general game: by making sure the given move doesn't put the player's king in check.
    NOTE: In chess (for those who don't know), it is illegal to move any piece if, at the end of
    the move, your king will be in check [possible to be captured by any enemy piece]
    This last check I want to do in the following way:
    1) copy/clone the entire PieceManager object
    2) in this copied object, actually do the move
    3) still in the copied/cloned object, see if the moving player's king is now in check
    4) based on this evaluation, execute the move in the original PieceManger object or don't...
    The Problem:
    When I clone this PieceManager object, its 'pieces' Vector is obviously also cloned.
    BUT it seems that the cloned 'pieces' Vector references the same ChessPiece objects
    as those referenced by the original 'pieces' Vector; ie the 2 Vectors are sharing the same Objects.
    Thus, when I actually execute the move in the test/cloned PieceManager object,
    the original PieceManager's corresponding piece is moved too (well, it seems it is the same piece...).
    I am pretty stuck with this.
    I've tried the Vector clone method; it doesn't seem to copy the objects, but create another reference
    to the same objects, as I've said.
    I've tried cloning the entire object ; also not helping......
    I'd love any comments, helpful pointers, suggestions.
    Also any comments on my program structure... is a Vector the best tool for this job?
    Thanks very much -
    lutha

    Hi all, OP here.
    Ok thanks guys for all your posts...
    two points:
    1) I have tried the "copy constructor", and it seems to be doing the same thing. (ie 'shallow clone')
    What's really frustrating me is that nothing I do seems to actually physically copy the Vector's objects
    to new, separate copies of those objects...
    I had my PieceManager class implement Cloneable (just in case - not too sure on that one; in fact I
    commented that out later), and I overrode the clone method like this:
    public Object clone ()
            PieceManager pm = new PieceManager ();
            Vector pcs = new Vector ();
            // Enumeration e = pieces.elements ();
            //while (e.hasMoreElements ())
            //    ChessPiece p = (ChessPiece) e.nextElement ();
            //pcs.add ();
            //}  // still references the same objects!!
            pieces.trimToSize ();
            int size = pieces.size ();
            Object[] arr = new Object [size];
            Object[] initial = pieces.toArray ();
            System.arraycopy (initial, 0, arr, 0, size);
            for (int i = 0 ; i < size ; i++)
                ChessPiece p = (ChessPiece) arr ;
    pcs.add (p);
    pm.pieces = pcs;
    return pm;
    This all still does the same 'shallow cloning'...
    2) m.winter, my ChessPiece objects are not immutable - they have a co-ordinate field that
    changes as they are moved. This is for getting as called by another object, and for checking in
    the ChessPiece's own internal method for checking whether the passed-in square co-ordinate
    is a valid destination.
    Anyway, I don't think that's the main issue here. How can I properly clone/copy a Vector, resulting
    in :
    a) the original Vector
    b) a new, totally unrelated Vector.
    Thanks again all for your input.
    regards,
    lutha

  • Multiple instances of one anonymous class

    Hi,
    I am implementing the Command pattern for an interpreter. I've created a Command class to describe the common behavior of all commands and create anonymous classes to manage the few exceptions I have. This design was chosen because I have numerous commands very similar and only a few exception, and I didn't wanted to create one class by command (the ration exception/normal is really low).
    registerCommand(new Command("commandName1", specificParameters...));
    registerCommand(new Command("commandName2", specificParameters...));
    registerCommand(new Command("exception3", specificParameters...)
        protected void execute()
          exceptional treatment...
    registerCommand(new Command("commandName4", specificParameters...));I came to the point that I have two exceptions that extend the Command class in the same way and I was asking if it is possible to create two object instances of the same anonymous class?
    Or asked differently, can one confirm that generally, anonymous classes object instances are unique?
    Thanks

    OK, perhaps I wasn't clear enough...
    Let's go with an example:
    registerCommand(new Command("exception3", specificParameters...)
        protected void execute()
          x = 1;
    registerCommand(new Command("exception4", specificParameters...)
        protected void execute()
          x = 1;
      });This code fragment creates 2 objects instances of 2 different anonymous classes. You can see that these classes have exactly the same definition (but are different), and the 2 instances are different (at least because of new instruction and that the constructor arguments are different, select the whatever reason you like).
    This new Command(..) {...} syntax defines in the same instruction an instance and an anonymous class. I would like to define an anonymous class and create 2 instances from the same anonymous class. I feel no need to name the class as only 2 instances will ever been created. And I was wondering if it is possible...
    I hope it's clearer now :)

  • Some generic anonymous class overriding methods compile, while others don't

    I have the following (stripped-down) code. The abstract class SessionHandler<T> is used by other code to define and run an operation that needs a session to something. This is best done in my code with anonymous classes, because of the shear number of operations defined. In the EntityOps<T> class, these work great. But, in the last class shown here, SomeClass, the anonymous class definition fails, though the semantics are almost identical. (List<T> vs.List<AnotherClass>) What am I doing wrong here? Or is this a bug in Java?
    Thanks, Tom
    public interface IEntityOps<T> {
        T get();
        List<t> getAll();
    public abstract class SessionHandler<T> {
        abstract T handle(Session session) throws Throwable;
        public final T perform() {
            ... calls handle(session) ...
    // These anonymous class definitions compile fine!
    public class EntityOps<T> implements IEntityOps<T> {
        public T get() {
            T ret = null;
            ret = new SessionHandler<T>() {
                T handle(Session s) throws Throwable {
                    T ret = (some T object calculation);
                    return ret;
            }.perform();
            return ret;
        public List<T> getAll() {
            T ret = null;
            return new SessionHandler<List<T>>() {
                List<T> handle(Session s) throws Throwable {
                    List<T> ret = (some List<T> calculation);
                    return ret;
            }.perform();
    // This anonymous class definition fails with the error:
    // "SomeClass.java": <anonymous someMethod> is not abstract and does not override abstract method handle()
    //     in SessionHandler at line XX, column XX
    public class SomeClass {
        public List<AnotherClass> someMethod() throws {
            List<AnotherClass> ret = null;
            ret = new SessionHandler<List<AnotherClass>>() {
                List<AnotherClass> handle(Session s) throws Throwable {
                    List<AnotherClass> ret = (some List<AnotherClass> calculation);
                    return ret;
            }.perform();
            return ret;
    }

    I added @Override above the abstract method override, and it provides this additional error:
    "HousingConfigImpl.java": method does not override a method from its superclass at line 382, column 17
    I have also reconstructed the code layout in a separate set of classes that have no dependancies, but there's no error coming from these!
    public class CustomThing {
    public interface ISomeInterface<T> {
        List<T> interfaceMethod();
    public abstract class SomeAbstractClass<T> {
        private Class _c = null;
        public SomeAbstractClass(Class c) {
            _c = c;
        protected Class getC() {
            return _c;
        public abstract T methodToOverride(Object neededObject) throws Throwable;
        public final T finalMethod() {
            try {
                return methodToOverride(new Object());
            } catch(Throwable e) {
                throw new RuntimeException(e);
    import java.util.List;
    import java.util.Collections;
    public class SomeInterfaceImpl<T> implements ISomeInterface<T> {
        public List<T> interfaceMethod() {
            return new SomeAbstractClass<List<T>>(CustomThing.class) {
                public List<T> methodToOverride(Object neededObject) throws Throwable {
                    return Collections.emptyList();
            }.finalMethod();
    import java.util.Collections;
    import java.util.List;
    public class SomeOtherClass {
        public List<CustomThing> someMethod() {
            return new SomeAbstractClass<List<CustomThing>>(CustomThing.class) {
                public List<CustomThing> methodToOverride(Object neededObject) throws Throwable {
                    return Collections.emptyList();
            }.finalMethod();
    }So, there's something about my code that causes it to be, somehow, different enough from the example provided above so that I get the error. The only differences in the override method definitions in my actual code are in the return type, but those are different in the example above as well. Here are the class declarations, anonymous abstract class creation statements, and abstract method declarations from the actual code.
    public abstract class SessionHandler<T> {
        abstract T handle(Session session) throws Throwable;
    public class EntityOps<T> implements IEntityOps<T> {
                return new SessionHandler<List<T>>(_mgr, _c, "getAll" + _c.getName()) {
                    List<T> handle(Session s) throws Throwable {
    public class HousingConfigImpl implements IHousingConfigOperations, ISessionFactoryManager {
                ret = new SessionHandler<List<Tenant>>((ISessionFactoryManager)this, Housing.class, "getTenantsInNeighborhood") {
                    List<Housing> handle(Session s) throws Throwable {I can't for the life of me see any syntactical difference between my example and the real code. But, one works and the other doesn't.

  • ABAP Class reference in persistent container

    Hi all,
    Has anyone ever tried to read an abap class reference from a rule container in the rule's function module?
    This doesn't seem to work, unless I am doing something wrong...
    Here is the scenario:
    I have an abap class ZCL_CLASS instantiated in my workflow container. In one of my workflow steps I pass that class object reference to a rule (Function Module based). In the rule function module I use macro swc_get_element to try to get the class object reference. And there it is not getting anything.
    I have already tried the following:
    - Try to run macro swc_container_to_runtime on the rule container before retrieving the object reference -> doesn't work. The internal table ac_container doesn't even look different before and after having run this macro.
    - Try to replace the declaration of include <CNTN01> by <CNTN02> + <CNTN03>. Doesn't change anything either.
    When I look at ac_container in debugging it seems my object reference is there but looks a bit strange:
    ELEMENT | TAB_INDEX | ELEMLENGTH | TYPE | VALUE
    WFIBF_PORTAB | 000011 | 004 | u | SWFTSTRUCT
    WFIBF_PORTAB | 000012 | 032 | C | STEP
    WFIBF_PORTAB | 000014 | 032 | C | 1CCC1000C
    WFIBF_PORTAB | 000015 | 104 | C | <object key>    <class>    CL
    Any idea of how I should proceed to retrieve my object reference?
    For the moment the workaround I found is to pass the object key to the rule and to reinstantiate the class in the rule function module. Not a very elegant solution...
    Thanks in advance and kind regards,
    Patrick

    Hi Mike,
    I understand what you're saying. But the problem is that the swc_get_element macro does not even get me the LPOR value, and therefore I can't call the FIND_BY_LPOR method.
    That means I have two solutions:
    - Passing the LPOR instead of the object reference to the rule container => Not a very nice solution, for many different reasons.
    - Find an alternative to swc_get_element to get the LPOR value.
    I had a look at class cl_swf_cnt_container, and it seems it can do the trick for me.
    So what I will finally do is:
    1. Convert the BOR container into an instance of cl_swf_cnt_container.
      DATA: lo_cnt    TYPE REF TO if_swf_cnt_container,
                 lt_container TYPE swconttab.
      lt_container[] = ac_container[].
      TRY.
          CALL METHOD cl_swf_cnt_container=>if_swf_cnt_conversion~create_from_bor_container
            EXPORTING
              values                = lt_container
            RECEIVING
              container           = lo_cnt.
        CATCH cx_swf_utl_obj_create_failed.
      ENDTRY.
    2. Get my container element.
    DATA: lo_myobj TYPE REF TO zcl_class.
    CALL METHOD lo_cnt->if_swf_ifs_parameter_container~get
      EXPORTING
        name       = 'MyContainerElement'
      IMPORTING
        value      = lo_myobj
    I didn't take the time to debug that deep in the standard SAP code, but I assume the if_swf_ifs_parameter_container~get re-instantiates my class for me.
    Please feel free to comment.
    Kind regards,
    Patrick

  • Obtaining a reference to an object created in another page

    Hello, In my webapp, i have a controller servlet which delegates the task to appropriate handler classes. My handler class performs the database access, then packages the result set object into a vector. I then create a new object of a javabean with a setPost() method which houses the output. My question is after this is done i forward control to the appropriate jsp for display. But how can i reference the object created in the page before. Will the request.setAttribute() method work for passing the reference to the object, to that jsp page? In other words i just want to access an object created in a different sevlet. Any help would be much appreciated
    thanks
    Gabriel

    Hi
    Yes, if you set the attribute, in this case the Java Bean in the request, it will be available in the JSP to where the request has been forwarded. Note however that the Object's lifetime is limited by that of the request. For Objects which need longer lifetimes you could place them either in the session or the ServletContext. The latter case will give the Object application wide scope and also a lifetime limited only by the lifetime of the application.
    Good Luck!
    Eshwar Rao
    Developer Technical Support
    Sun microsystems inc
    http://www.sun.com/developers/support

Maybe you are looking for

  • Making divs expand to the height of the highest div

    I'm currently building my portfolio website. I'm not a coder and find it difficult so I really need simple answers if possible please. The page I'm working on can be found here: http://www.infomaticfilms.com/jack/jrimg/g_and_d.htm. It's far from fini

  • [Solved]conky-lua

    I was trying to install conky-lua when I got this error, and I don't know how to proceed from here. Please help. Last edited by Laplace_ (2009-12-29 05:15:15)

  • Sort picking list by storage bin or material in customizing

    Hello Gurus,      How can I sort picking list by storage bin or material in customizing? thanks very much!

  • BT Infinity 2 upgrade has left me without Internet...

    After what was supposed to be a simple upgrade from ADSL to BT Infinity, I have now been without any broadband at for a week and have been subjected to undoubtedly the worst customer service imaginable…. Here goes.   Tuesday 6 June, an engineer arriv

  • X505-Q8102x Sound Problem

    After automatic updates, the sound quit working properly. At first I thought it was newer games that were "too much" for the older computer to handle (Craft the World) but then also noticed that the same problems plague games that I know worked just