Anonymous Classes

Can you implement an interface on an anonymous class ?
(of course the anonymous class does not belongs or extends of an interface)
I know this sound strange but it's in a code I have to maintain and in order to make less changes as posible I want to try this.
ie.
public JTable createTable()
        //I want this JTable to implent an ActionListerner or any Interface,
        //is this posible?
        return new JTable()
}Thanks!
que_genio

//I want this JTable to implent an ActionListerner or any Interface,
//is this posible?
return new JTable()
{Yes use an anonymous inner class

Similar Messages

  • 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

  • Inner/anonymous classes

    I have searched and found other versions of this question, but haven't run across the answer yet, so...
    My program runs correctly from the command line.
    When I try to execute the .jar file using the java -jar TIS.jar command I get a noclassdeffound error. The class it can't find happens to be the first inner class it encounters. I have checked the jar file, and the class is in there. Is there a problem with java finding inner classes in jar files?
    Some supporting info:
    here is my manifest:
    Manifest-Version: 1.0
    Created-By: 1.4.1_01 (Sun Microsystems Inc.)
    Main-Class: ToolInventorySystem
    class not found has the name ControlScreen$addToolListener.class
    I found in another post that the $ indicates either an anonymous class or an inner class (I have both in my programs)
    Thanks in advance

    Wow, that formatting didn't work, let me try that again...
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class ControlScreen extends JFrame {
         //Fields for screen size
         public static final int DEFAULT_WIDTH = 500;
         public static final int DEFAULT_HEIGHT = 500;
         public ControlScreen(){
              setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
              Container contentPane = getContentPane();
              JPanel SelectButtonPanel = new JPanel();
              //Selection Buttons     
              //add new tools
              JButton addToolButton = new JButton("Add Tool");
              SelectButtonPanel.add(addToolButton);
              ActionListener atl = new AddToolListener();
              addToolButton.addActionListener(atl);
              //add new projects
              JButton addProjectButton = new JButton("Add Project");
              SelectButtonPanel.add(addProjectButton);
              ActionListener apl = new AddProjectListener();
              addProjectButton.addActionListener(apl);
              //check out tools
              JButton checkOutToolButton = new JButton("Check Out Tools");
              SelectButtonPanel.add(checkOutToolButton);
              ActionListener cotl = new CheckOutToolListener();
              checkOutToolButton.addActionListener(cotl);
              //return tools
              JButton returnToolButton = new JButton("Return Tool");
              SelectButtonPanel.add(returnToolButton);
              ActionListener rtl = new ReturnToolListener();
              returnToolButton.addActionListener(rtl);
              //generate bill
              JButton billButton = new JButton("Create Billing Statement");
              SelectButtonPanel.add(billButton);
              ActionListener bl = new BillListener();
              billButton.addActionListener(bl);
              contentPane.add(SelectButtonPanel, BorderLayout.SOUTH);
         }//close constructor
         class AddToolListener implements ActionListener{
         public void actionPerformed(ActionEvent event){
              //This class will display the tool entry frame
              ToolScreen ts = new ToolScreen();
              ts.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              ts.show();
              }//close method
         }//close addToolListener
         class AddProjectListener implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   //This class will display the project entry frame
                   ProjectScreen ps = new ProjectScreen();
                   ps.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   ps.show();
              }//close method
         }//close addprojectlistener
         class CheckOutToolListener implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   //this class displays the list of active projects
                   Project[] projectList = TISController.getProjectList();
                   CheckoutProjectListDisplayScreen cplds = new CheckoutProjectListDisplayScreen(projectList);
                   cplds.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   cplds.show();
              }//close method
         }//close check out tool listener
         class ReturnToolListener implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   //this class displays the list of active projects
                   Project[] projectList = TISController.getProjectList();
                   ReturnProjectListDisplayScreen rplds = new ReturnProjectListDisplayScreen(projectList);
                   rplds.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   rplds.show();
              }//close method
         }//close check out tool listener
         class BillListener implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   //this class displays the list of active projects
                   Project[] projectList = TISController.getProjectList();
                   BillProjectListDisplayScreen bplds = new BillProjectListDisplayScreen(projectList);
                   bplds.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   bplds.show();
              }//close method
         }//close create bill listener
    }//close Control Screen class

  • How to access class variables in anonymous class??.

    I have a boolean class level variable. Fom a button action , this boolean will set to true and then it used in anonymous class. In anonymous class, I am getting default value instead of true. Could u anyone help in this plzzz.

    first of all, you don't want parent because that is something that Containers use to remember their containment hierarchy. you are thinking of super which is also incorrect, because that has to do with inheritance.
    the problem here is a scoping problem. you generally would use final if you were accessing variables in an anonymous class that are in the local scope. in this case, you just need to create some test code and play with it. snip the code below and play with it. it shows both the given examples and some additional ways to change/display class variables.
    good luck, hackerx
    import javax.swing.*;
    import java.awt.event.*;
    public class Foo extends JPanel
         private boolean the_b = true;
         public static void main(String[] args)
              Foo f = new Foo();
              JFrame frame = new JFrame();
              frame.getContentPane().add(f);
              frame.pack();
              frame.show();
         public Foo()
              // get your button
              JButton b = new JButton("Not!");
              b.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        // *** uncomment these to play around ***
                        // Foo.this.the_b = false; // this will work, but unnecessary
                        // the_b = false; // this works fine too
                        notFoo();
              this.add(b);
              // something to show the value that accesses a class variable
              // using an inner class instead of final nonsense
              DisplayThread t = new DisplayThread();
              t.start();
         private void notFoo()
              the_b = !the_b;
         class DisplayThread extends Thread
              public void run()
                   while(true)
                        System.err.println("boolean value: " + the_b);
                        try {
                        sleep(1000);
                        } catch(InterruptedException ie) {}
    }

  • Static variables in anonymous classes ..

    How can i access a static variable from an anonymous class ..
    class A{
    outerMeth(){
    Interface anon=new Interface(){
    static int i;
    // how can i acess 'i' ..
    thanx in advance ..

    sorry .. not a valid question ..
    static var are not allowed in anonymous/inner classes ..
    sorry ..
    ignore this one ..

  • Checked Exception and Anonymous classes

    Hi I am refering to java certification book that says : If a checked exception is thrown during the execution of initializer expression, then it has to be caught and handled. This restriction does not apply to instance initializer expressions in anonymous classes.
    I have codes for the above statement but failed to get the correct result. Is there some problem with the code :
    class RoomOccupancyTooHighException extends RuntimeException {} // (1) Unchecked Exception
    class TooManyHotelsException extends Exception {}           // (2) Checked Exception
    class base
         public void fun()
              System.out.println("base");
    class derived
         public static base funtion()
              return new base()
                                       int a = fu();
                                       int fu()
                                            if(a==1)
                                            throw new TooManyHotelsException();
                                            return 100;
                                       public void fun()
                                            System.out.println("derived");
         public static void main(String str[])
              base b = funtion();
              b.fun();
    }

    In anonynous class initialisation you don't need to declare the exception but you still need to handle it in the calling code.
    The code you provided does not compile for that reason.

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

  • ActionListener as nested class, anonymous class etc.

    I'm programing my own text editor and im trying to decide in what way to implement an ActionListener for JMenuItems.
    I've got 3 possible ideas of how to implement it.
    First way is to implement the ActionListener in the same class as the JMenu and use a switch statement or a fairly long if-else statement.
    Second way is to create nested classes for each ActoinEvent.
    public class OuterClass {
         //Some random code here...
         private class ActionClass implements ActionListener{
              public void actionPerformed(ActionEvent e) {
                   //Random code.
    }And final way is creating anonymous classes adding ActionListeners for each JMenuItem.
    menuItem.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) {
    });But i can't decide on wich of these are the moste correct and accepted way.
    Could someone point me to the right direction?
    Edited by: Idono on Jun 3, 2010 7:36 PM

    the only time you would do the first one would be if you wanted several ActionListeners to do the EXACT SAME THING.
    Then you just write the "actionClass" one time, and have each Component use it.
    private class ActionClass implements ActionListener{
              public void actionPerformed(ActionEvent e) {
                   //Random code.
    menuItem.addActionListener(new ActionClass());
    menuItem1.addActionListener(new ActionClass());
    menuItem2.addActionListener(new ActionClass());
    menuItem3.addActionListener(new ActionClass());But (as the other person mentioned) usually you use anonymous classes because each component has different actions.
    menuItem.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) { ... }
    menuItem1.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) { ... }
    menuItem2.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) { ... }
    });

  • Anonymous class instantiation expression with interface implementation??

    Is it possible to create an inline anonymous class instatiation expression that can implements an interface?
    For example:
    Frame myFrame = new Frame() implements WindowListner {
         public void WindowOpened(WindowEvent  e) {}
             +other interface methods....+
    }Apparently compiler doesn't like this code:(
    I know that I can create an extra named class with the interface, then instantiate it instead. But this is not what I want.
    (By the way, if someone wants to know why I want to do this, I say I think this may make my code simpler or look better, that's all:) )

    abstract class ListenerFrame extends Frame implements WindowListener {} This look pretty neat:)
    I guess I can rewrite my code then:
    abstract class FrameWithListener extends Frame
             implements WindowListener{}      //local class
    Frame myFrame = new FrameWithListener {
            public void WindowOpened {}
               blah, blah...
    }Not sure I can use abstarct class as local class, but otherwise I'll use it as a class member or some sort..
    Thank you for the reply
    Edited by: JavaToTavaL on Nov 27, 2009 4:04 AM
    Edited by: JavaToTavaL on Nov 27, 2009 4:04 AM

  • Anonymous class for Event handling isnt working

    my anonymous class is not working.i keep gettin an invalid method declaration. i think im either mispelling something somewhwere or missing a curly.
    public SpouseGUI(){
         add(new JButton("test"){
    addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent e){
                   JOptionPane.showMessageDialog(null,"hi","hi",3);
                   }//end method
              }//end action listener
    }//end anonymous class
                   setSize(100,100);
    setVisible(true);
    //end of constructor

    Yeah, you shouldn't use anonymous classes like that; that's not the purpose of anonymous classes. If you really, really, want to use an anonymous class, you will have to use a initializer block, like this:
    p.add(new JButton("test") {
        { // initializer block
            addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    // do something
    });But there is absolutely no point in doing that, it's much better to just create the button and add the action listener:
    JButton btn = new JButton("test");
    btn.addActionListener(...);
    add(btn);

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

  • Anonymous class

    I hava got a nested class like:
    public class Test {
        public static class MathArray {
         double[] array;
         MathArray(double[] array) {
             this.array = array;
         void warnNaN(double d) {
             if(((Double)d).isNaN())
              System.err.println("Warning: result is undefined");
         void applyFunction()
             for (int i = 0; i < array.length; i++) {
              double x = array;
              x = Math.sin(x);
              x = Math.sqrt(x);
              x = -x;
              array[i] = x;
              warnNaN(array[i]);
         void print() {
         for(int i = 0; i < array.length; i++)
              System.out.print(array[i] + (i < array.length-1?", ":"\n"));
    public static void main(String[] args) {
         MathArray te = new MathArray(new double[] {0.1, 2.23, 3.08});
         // apply -Sqrt(Sin(x)) to each element x in the array:
         te.applyFunction();
         te.print();
    i was asked to modified the code so that the functors are instances of anonymous classes
    i am not quite sure what to do, can anyone give me a hand please? thank you.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Like this?
    import java.util.*;
    interface Function {
        double op(double x);
    public class Test {
        static double[] map(double[] v, Function f) {
            double[] result = new double[v.length];
            for(int i=0; i<result.length; ++i) {
                result[i] = f.op(v);
    return result;
    public static void main(String[] args) {
    double[] data = {0, 1, 2, 3, 4};
    double[] squares = map(data, new Function(){
    public double op(double x) {return x*x;}
    double[] sqroots = map(data, new Function(){
    public double op(double x) {return Math.sqrt(x);}
    System.out.println(Arrays.toString(squares));
    System.out.println(Arrays.toString(sqroots));

  • Access fo Method parameters to Anonymous Class ?

    Can somebody please provide some more information on the statement below? I am also searching for some sample code implementations of it. It would help the cause better.
    +"Methods of the object of the anonymous class need access to final local variables and method parameters belonging to the method in which the anonymous class is defined. "+
    Thanks in Advance

    We're concerned here with "local" classes, i.e. classes defined inside methods (not all anonymous classes are local, and not all local classes are anonymous).
    The thing about local classes is that, unlike local variables etc., instances of a local class may survive the method returning. For example a local class might be a listener which gets added to a swing component, it could be a Runnable that get's launched as a thread.
    Local classes get to access local variables and parameters of the method in which they are declared but the variables or parameters have to be declared final because, since the class needs to be able to access the value of the local variable even after the method exits, and the variable ceases to exist, what actually happens it that the value of the variable is copied into a special field of the anonymous class, and if the variable could be changed after the class was defined, the two copies would then disagree.

Maybe you are looking for

  • [JS] Find invalid language

    (Related to InDesignSecrets Script to change the language of all text on document) I'm trying to identify, and then replace "invalid" languages -- the ones that creep in with Word document and InDesign blithely ignores because it's not in its interna

  • Array to ColorFrame not accepting data.

    I am attempting to interface with a IP-cam and generate an .AVI file from the captured images taken N times per second, however I am having issues with a fundamental step, Capturing the images from my IP-cam is easy, done it for another project. When

  • Trying to create tasks in PWA

    New Project server 2013 PWA instance When you try and create a new project in PWA (or add a task to an existing schedule) you receive the following Error message. An error occurred while opening your project. Give us a few minutes and try again. If t

  • How to create a slide show using Flash and some pictures

    I looked at many books but I can't find how I can make a slide show using flash. Can anyone give me some idea how I might go with this?

  • Ipad Mini - Can I use wifi without sim card?

    I'm thinking about buying Ipad Mini but I don't know if I can use my home wifi connection without a sim card. Should I buy it too? How can I use Ipad Mini without a sim card? What can I do without it?