Name binding in anonymous class vs. method

Hi,
The following program prints 0, then 3. Can anyone explain why the inner class in method() uses field 'x', while method1() uses parameter 'x'? Is this case well-defined by the Java spec?
Thanks,
Shlomy
public abstract class A implements Runnable {
     public int x = 0;
     public static void method(final int x) {
          A a = new A() {
               public void run() {
                    System.err.println(x);          
          a.run();
     public static void method1(final int x) {
          System.err.println(x);
     public static void main(String [] args) {
          method(3);
          method1(3);
}

Hello Shlomy,
John Rose wrote a [blog post|http://blogs.sun.com/jrose/entry/scope_ambiguities_between_outer_and] regarding this topic. Originally (before 1.4) you would have gotten an error, today you can't count on "Mother Compiler" to point out ambiguities for you.
Quote from the blog post:
If there is no such qualifier possible, the intended variable is a local, and it may therefore be renamed to remove the ambiguity.With kind regards
Ben
Edited by: BenSchulz on Feb 16, 2010 8:28 AM added quote

Similar Messages

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

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

  • 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 get the name of the current class...

    I'm writing a method for a superclass, to be used by all dervied classes. In the method, I want to be able to find out what class is running, and then use the instanceof operation on it. How do I do this? Something like:
    String className = this.getClass().getName();
    Class c = Class.forName(className);
    if (form instanceof c)
         System.out.println(" Yes");The compiler is telling me "the type named c is not defined." What am I doing wrong? Is there a better way to do this? I think there should be because the forName method loads the class, but all I want is the name in a form I can use the instanceof operation with.

    The instanceof operator takes an actual class name, not a reference to a Class. Sounds weird but perhaps an example would be more appropriate:
    if(obj instanceof MyClass.class)
    not
    Class c = Class.forName("MyClass");
    if(obj instanceof c)Fortunately Class provides methods that do pretty much the same as the instanceof operator:
    Class c = Class.forName("MyClass");
    if(c.instanceOf(obj))
    ...Hope this helps.

  • How to achive the functionality of Class.cast method in Java 1.4.2

    Hi Everyone!!
    Does anyone know of an api or a class that would let you achieve the same functionality of Class.cast method, i am using Java 1.4.2.
    Thanks,
    Pratik

    well i have bunch of code that is written for 1.5,
    but it need to be work with 1.4 as well.obviously, but what is your code doing that you need to use Class.cast functionality? There is a relatively specialized use for this method, and I don't see all that many programs using it. It basically allows you to cast to an anonymous object to the class defined by your Class object, which is only necessary if you don't really know what class your Class object represents. I'm not saying there isn't a need for it in some apps, but I'm just curious what you're doing...

  • 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 :)

  • Could you please send me the material Opps concepts Classes and Methods

    Hi Experts,
    I am working on Opps concepts.I am new to this concept.
    Could you please send me the detailed presentation on Abap oops.
    Thanks inadvance,
    Regards,
    Rekha.

    Hi this will help u.
    OOPs ABAP uses Classes and Interfaces which uses Methods and events.
    If you have Java skills it is advantage for you.
    There are Local classes as well as Global Classes.
    Local classes we can work in SE38 straight away.
    But mostly it is better to use the Global classes.
    Global Classes or Interfaces are to be created in SE24.
    SAP already given some predefined classes and Interfaces.
    This OOPS concepts very useful for writing BADI's also.
    So first create a class in SE 24.
    Define attributes, Methods for that class.
    Define parameters for that Method.
    You can define event handlers also to handle the messages.
    After creation in each method write the code.
    Methods are similar to ABAP PERFORM -FORM statements.
    After the creation of CLass and methods come to SE38 and create the program.
    In the program create a object type ref to that class and with the help of that Object call the methods of that Class and display the data.
    Example:
    REPORT sapmz_hf_alv_grid .
    Type pool for icons - used in the toolbar
    TYPE-POOLS: icon.
    TABLES: zsflight.
    To allow the declaration of o_event_receiver before the
    lcl_event_receiver class is defined, decale it as deferred in the
    start of the program
    CLASS lcl_event_receiver DEFINITION DEFERRED.
    G L O B A L I N T E R N A L T A B L E S
    *DATA: gi_sflight TYPE STANDARD TABLE OF sflight.
    To include a traffic light and/or color a line the structure of the
    table must include fields for the traffic light and/or the color
    TYPES: BEGIN OF st_sflight.
    INCLUDE STRUCTURE zsflight.
    Field for traffic light
    TYPES: traffic_light TYPE c.
    Field for line color
    types: line_color(4) type c.
    TYPES: END OF st_sflight.
    TYPES: tt_sflight TYPE STANDARD TABLE OF st_sflight.
    DATA: gi_sflight TYPE tt_sflight.
    G L O B A L D A T A
    DATA: ok_code LIKE sy-ucomm,
    Work area for internal table
    g_wa_sflight TYPE st_sflight,
    ALV control: Layout structure
    gs_layout TYPE lvc_s_layo.
    Declare reference variables to the ALV grid and the container
    DATA:
    go_grid TYPE REF TO cl_gui_alv_grid,
    go_custom_container TYPE REF TO cl_gui_custom_container,
    o_event_receiver TYPE REF TO lcl_event_receiver.
    DATA:
    Work area for screen 200
    g_screen200 LIKE zsflight.
    Data for storing information about selected rows in the grid
    DATA:
    Internal table
    gi_index_rows TYPE lvc_t_row,
    Information about 1 row
    g_selected_row LIKE lvc_s_row.
    C L A S S E S
    CLASS lcl_event_receiver DEFINITION.
    PUBLIC SECTION.
    METHODS:
    handle_toolbar FOR EVENT toolbar OF cl_gui_alv_grid
    IMPORTING
    e_object e_interactive,
    handle_user_command FOR EVENT user_command OF cl_gui_alv_grid
    IMPORTING e_ucomm.
    ENDCLASS.
    CLASS lcl_event_receiver IMPLEMENTATION
    CLASS lcl_event_receiver IMPLEMENTATION.
    METHOD handle_toolbar.
    Event handler method for event toolbar.
    CONSTANTS:
    Constants for button type
    c_button_normal TYPE i VALUE 0,
    c_menu_and_default_button TYPE i VALUE 1,
    c_menu TYPE i VALUE 2,
    c_separator TYPE i VALUE 3,
    c_radio_button TYPE i VALUE 4,
    c_checkbox TYPE i VALUE 5,
    c_menu_entry TYPE i VALUE 6.
    DATA:
    ls_toolbar TYPE stb_button.
    Append seperator to the normal toolbar
    CLEAR ls_toolbar.
    MOVE c_separator TO ls_toolbar-butn_type..
    APPEND ls_toolbar TO e_object->mt_toolbar.
    Append a new button that to the toolbar. Use E_OBJECT of
    event toolbar. E_OBJECT is of type CL_ALV_EVENT_TOOLBAR_SET.
    This class has one attribute MT_TOOLBAR which is of table type
    TTB_BUTTON. The structure is STB_BUTTON
    CLEAR ls_toolbar.
    MOVE 'CHANGE' TO ls_toolbar-function.
    MOVE icon_change TO ls_toolbar-icon.
    MOVE 'Change flight' TO ls_toolbar-quickinfo.
    MOVE 'Change' TO ls_toolbar-text.
    MOVE ' ' TO ls_toolbar-disabled.
    APPEND ls_toolbar TO e_object->mt_toolbar.
    ENDMETHOD.
    METHOD handle_user_command.
    Handle own functions defined in the toolbar
    CASE e_ucomm.
    WHEN 'CHANGE'.
    PERFORM change_flight.
    LEAVE TO SCREEN 0.
    ENDCASE.
    ENDMETHOD.
    ENDCLASS.
    S T A R T - O F - S E L E C T I O N.
    START-OF-SELECTION.
    SET SCREEN '100'.
    *& Module USER_COMMAND_0100 INPUT
    MODULE user_command_0100 INPUT.
    CASE ok_code.
    WHEN 'EXIT'.
    LEAVE TO SCREEN 0.
    ENDCASE.
    ENDMODULE. " USER_COMMAND_0100 INPUT
    *& Module STATUS_0100 OUTPUT
    MODULE status_0100 OUTPUT.
    DATA:
    For parameter IS_VARIANT that is sued to set up options for storing
    the grid layout as a variant in method set_table_for_first_display
    l_layout TYPE disvariant,
    Utillity field
    l_lines TYPE i.
    After returning from screen 200 the line that was selected before
    going to screen 200, should be selected again. The table gi_index_rows
    was the output table from the GET_SELECTED_ROWS method in form
    CHANGE_FLIGHT
    DESCRIBE TABLE gi_index_rows LINES l_lines.
    IF l_lines > 0.
    CALL METHOD go_grid->set_selected_rows
    EXPORTING
    it_index_rows = gi_index_rows.
    CALL METHOD cl_gui_cfw=>flush.
    REFRESH gi_index_rows.
    ENDIF.
    Read data and create objects
    IF go_custom_container IS INITIAL.
    Read data from datbase table
    PERFORM get_data.
    Create objects for container and ALV grid
    CREATE OBJECT go_custom_container
    EXPORTING container_name = 'ALV_CONTAINER'.
    CREATE OBJECT go_grid
    EXPORTING
    i_parent = go_custom_container.
    Create object for event_receiver class
    and set handlers
    CREATE OBJECT o_event_receiver.
    SET HANDLER o_event_receiver->handle_user_command FOR go_grid.
    SET HANDLER o_event_receiver->handle_toolbar FOR go_grid.
    Layout (Variant) for ALV grid
    l_layout-report = sy-repid. "Layout fo report
    Setup the grid layout using a variable of structure lvc_s_layo
    Set grid title
    gs_layout-grid_title = 'Flights'.
    Selection mode - Single row without buttons
    (This is the default mode
    gs_layout-sel_mode = 'B'.
    Name of the exception field (Traffic light field) and the color
    field + set the exception and color field of the table
    gs_layout-excp_fname = 'TRAFFIC_LIGHT'.
    gs_layout-info_fname = 'LINE_COLOR'.
    LOOP AT gi_sflight INTO g_wa_sflight.
    IF g_wa_sflight-paymentsum < 100000.
    Value of traffic light field
    g_wa_sflight-traffic_light = '1'.
    Value of color field:
    C = Color, 6=Color 1=Intesified on, 0: Inverse display off
    g_wa_sflight-line_color = 'C610'.
    ELSEIF g_wa_sflight-paymentsum => 100000 AND
    g_wa_sflight-paymentsum < 1000000.
    g_wa_sflight-traffic_light = '2'.
    ELSE.
    g_wa_sflight-traffic_light = '3'.
    ENDIF.
    MODIFY gi_sflight FROM g_wa_sflight.
    ENDLOOP.
    Grid setup for first display
    CALL METHOD go_grid->set_table_for_first_display
    EXPORTING i_structure_name = 'SFLIGHT'
    is_variant = l_layout
    i_save = 'A'
    is_layout = gs_layout
    CHANGING it_outtab = gi_sflight.
    *-- End of grid setup -
    Raise event toolbar to show the modified toolbar
    CALL METHOD go_grid->set_toolbar_interactive.
    Set focus to the grid. This is not necessary in this
    example as there is only one control on the screen
    CALL METHOD cl_gui_control=>set_focus EXPORTING control = go_grid.
    ENDIF.
    ENDMODULE. " STATUS_0100 OUTPUT
    *& Module USER_COMMAND_0200 INPUT
    MODULE user_command_0200 INPUT.
    CASE ok_code.
    WHEN 'EXIT200'.
    LEAVE TO SCREEN 100.
    WHEN'SAVE'.
    PERFORM save_changes.
    ENDCASE.
    ENDMODULE. " USER_COMMAND_0200 INPUT
    *& Form get_data
    FORM get_data.
    Read data from table SFLIGHT
    SELECT *
    FROM zsflight
    INTO TABLE gi_sflight.
    ENDFORM. " load_data_into_grid
    *& Form change_flight
    Reads the contents of the selected row in the grid, ans transfers
    the data to screen 200, where it can be changed and saved.
    FORM change_flight.
    DATA:l_lines TYPE i.
    REFRESH gi_index_rows.
    CLEAR g_selected_row.
    Read index of selected rows
    CALL METHOD go_grid->get_selected_rows
    IMPORTING
    et_index_rows = gi_index_rows.
    Check if any row are selected at all. If not
    table gi_index_rows will be empty
    DESCRIBE TABLE gi_index_rows LINES l_lines.
    IF l_lines = 0.
    CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT'
    EXPORTING
    textline1 = 'You must choose a line'.
    EXIT.
    ENDIF.
    Read indexes of selected rows. In this example only one
    row can be selected as we are using gs_layout-sel_mode = 'B',
    so it is only ncessary to read the first entry in
    table gi_index_rows
    LOOP AT gi_index_rows INTO g_selected_row.
    IF sy-tabix = 1.
    READ TABLE gi_sflight INDEX g_selected_row-index INTO g_wa_sflight.
    ENDIF.
    ENDLOOP.
    Transfer data from the selected row to screenm 200 and show
    screen 200
    CLEAR g_screen200.
    MOVE-CORRESPONDING g_wa_sflight TO g_screen200.
    LEAVE TO SCREEN '200'.
    ENDFORM. " change_flight
    *& Form save_changes
    Changes made in screen 200 are written to the datbase table
    zsflight, and to the grid table gi_sflight, and the grid is
    updated with method refresh_table_display to display the changes
    FORM save_changes.
    DATA: l_traffic_light TYPE c.
    Update traffic light field
    Update database table
    MODIFY zsflight FROM g_screen200.
    Update grid table , traffic light field and color field.
    Note that it is necessary to use structure g_wa_sflight
    for the update, as the screen structure does not have a
    traffic light field
    MOVE-CORRESPONDING g_screen200 TO g_wa_sflight.
    IF g_wa_sflight-paymentsum < 100000.
    g_wa_sflight-traffic_light = '1'.
    C = Color, 6=Color 1=Intesified on, 0: Inverse display off
    g_wa_sflight-line_color = 'C610'.
    ELSEIF g_wa_sflight-paymentsum => 100000 AND
    g_wa_sflight-paymentsum < 1000000.
    g_wa_sflight-traffic_light = '2'.
    clear g_wa_sflight-line_color.
    ELSE.
    g_wa_sflight-traffic_light = '3'.
    clear g_wa_sflight-line_color.
    ENDIF.
    MODIFY gi_sflight INDEX g_selected_row-index FROM g_wa_sflight.
    Refresh grid
    CALL METHOD go_grid->refresh_table_display.
    CALL METHOD cl_gui_cfw=>flush.
    LEAVE TO SCREEN '100'.
    ENDFORM. " save_changes
    chk this blog
    /people/vijaybabu.dudla/blog/2006/07/21/topofpage-in-alv-using-clguialvgrid
    with regards,
    Hema.
    pls give points if helpful.

  • [svn] 3540: Fix for missing name of the exception class, when @ throw is used.

    Revision: 3540
    Author: [email protected]
    Date: 2008-10-09 11:20:44 -0700 (Thu, 09 Oct 2008)
    Log Message:
    Fix for missing name of the exception class, when @throw is used.
    Also fixes for:
    SDK-17212 - Add a line feed between messages in the ASDoc validation_errors.log file.
    SDK-17242 - The Constants.as and GlobalFunctions.as classes from system classes need to have their content added to __Global__.xml
    SDK-17256 - For methods of the mx.components.Group class, args or return values of type Object do not appear in the ASDoc output.
    QA: Yes
    Doc:
    Tests: checkintests
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-17212
    http://bugs.adobe.com/jira/browse/SDK-17242
    http://bugs.adobe.com/jira/browse/SDK-17256
    Modified Paths:
    flex/sdk/trunk/asdoc/templates/class-files.xslt
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsDocUtil.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/ClassTable.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/TopLevelClassesGenerator.ja va

    Revision: 3540
    Author: [email protected]
    Date: 2008-10-09 11:20:44 -0700 (Thu, 09 Oct 2008)
    Log Message:
    Fix for missing name of the exception class, when @throw is used.
    Also fixes for:
    SDK-17212 - Add a line feed between messages in the ASDoc validation_errors.log file.
    SDK-17242 - The Constants.as and GlobalFunctions.as classes from system classes need to have their content added to __Global__.xml
    SDK-17256 - For methods of the mx.components.Group class, args or return values of type Object do not appear in the ASDoc output.
    QA: Yes
    Doc:
    Tests: checkintests
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-17212
    http://bugs.adobe.com/jira/browse/SDK-17242
    http://bugs.adobe.com/jira/browse/SDK-17256
    Modified Paths:
    flex/sdk/trunk/asdoc/templates/class-files.xslt
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsDocUtil.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/ClassTable.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/TopLevelClassesGenerator.ja va

  • How to implement classes and methods in badi's ?

    how to implement classes and methods in badi's? and where i have to write the code based on the requirement?can anyone explain me briefly?

    Hi
    Every BADI by default Implements an INTERFACE which already contains some methods with parameters.
    So you have to find the relavenet method based on the related paramters (by checking the fields in that paramters) you have to double click on the method and to write the code.
    see the doc
    DEFINING THE BADI
    1) execute Tcode SE18.
    2) Specify a definition Name : ZBADI_SPFLI
    3) Press create
    4) Choose the attribute tab. Specify short desc for badi.. and specify the type :
    multiple use.
    5) Choose the interface tab
    6) Specify interface name: ZIF_EX_BADI_SPFLI and save.
    7) Dbl clk on interface name to start class builder . specify a method name (name,
    level, desc).
    Method level desc
    Linese;ection instance methos some desc
    8) place the cursor on the method name desc its parameters to define the interface.
    Parameter type refe field desc
    I_carrid import spfli-carrid some
    I_connid import spefi-connid some
    9) save , check and activate…adapter class proposed by system is
    ZCL_IM_IM_LINESEL is genereated.
    IMPLEMENTATION OF BADI DEFINITION
    1) EXECUTE tcode se18.choose menuitem create from the implementation menubar.
    2) Specify aname for implementation ZIM_LINESEL
    3) Specify short desc.
    4) Choose interface tab. System proposes a name fo the implementation class.
    ZCL_IM_IMLINESEL which is already generarted.
    5) Specify short desc for method
    6) Dbl clk on method to insert code..(check the code in “AAA”).
    7) Save , check and activate the code.
    Some useful URL
    http://www.esnips.com/doc/e06e4171-29df-462f-b857-54fac19a9d8e/ppt-on-badis.ppt
    http://www.esnips.com/doc/10016c34-55a7-4b13-8f5f-bf720422d265/BADIs.pdf
    http://www.esnips.com/doc/43a58f51-5d92-4213-913a-de05e9faac0d/Business-Addin.doc
    http://www.esnips.com/doc/1e10392e-64d8-4181-b2a5-5f04d8f87839/badi.doc
    www.sapgenie.com/publications/saptips/022006%20-%20Zaidi%20BADI.pdf
    http://www.sapdevelopment.co.uk/enhance/enhance_badi.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/04/f3683c05ea4464e10000000a114084/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/e6/d54d3c596f0b26e10000000a11402f/content.htm
    http://help.sap.com/saphelp_nw2004s/helpdata/en/c2/eab541c5b63031e10000000a155106/frameset.htm
    Now write a sample program to use this badi method..
    Look for “BBB” sample program.
    “AAA”
    data : wa_flights type sflight,
    it_flights type table of sflight.
    format color col_heading.
    write:/ 'Flight info of:', i_carrid, i_connid.
    format color col_normal.
    select * from sflight
    into corresponding fields of table it_flights
    where carrid = i_carrid
    and connid = i_connid.
    loop at it_flights into wa_flights.
    write:/ wa_flights-fldate,
    wa_flights-planetype,
    wa_flights-price currency wa_flights-currency,
    wa_flights-seatsmax,
    wa_flights-seatsocc.
    endloop.
    “BBB”
    *& Report ZBADI_TEST *
    REPORT ZBADI_TEST .
    tables: spfli.
    data: wa_spfli type spfli,
    it_spfli type table of spfli with key carrid connid.
    *Initialise the object of the interface.
    data: exit_ref type ref to ZCL_IM_IM_LINESEL,
    exit_ref1 type ref to ZIF_EX_BADISPFLI1.
    selection-screen begin of block b1.
    select-options: s_carr for spfli-carrid.
    selection-screen end of block b1.
    start-of-selection.
    select * from spfli into corresponding fields of table it_spfli
    where carrid in s_carr.
    end-of-selection.
    loop at it_spfli into wa_spfli.
    write:/ wa_spfli-carrid,
    wa_spfli-connid,
    wa_spfli-cityfrom,
    wa_spfli-deptime,
    wa_spfli-arrtime.
    hide: wa_spfli-carrid, wa_spfli-connid.
    endloop.
    at line-selection.
    check not wa_spfli-carrid is initial.
    create object exit_ref.
    exit_ref1 = exit_ref.
    call method exit_ref1->lineselection
    EXPORTING
    i_carrid = wa_spfli-carrid
    i_connid = wa_spfli-connid.
    clear wa_spfli.
    Reward points for useful Answers
    Regards
    Anji
    Message was edited by:
            Anji Reddy Vangala

  • Debugging Classes and methods in a Function Module

    Folks
    While debugging a Function Module, I want to know which classes and methods are being called as part of this FM and want to put a breakpoint in this Class method and check the details of variables in this methods. How do I accomplish this ?
    Is the hierarchy that -  FM will have classes which will have methods or is it something different ?
    Thanks

    Goto SE24->Give class name as CL_EXITHANDLER->Display->double click on get_instance mathod->Now u will go inside the method->Now put break point on the cl_exithandler.Now go to any transaction code ( se37) and pass dat..U will see that it will be stopped on the break point which u set on the cl_exithandler...
    than can debug further.

  • Call Java Class and Methods from ABAP

    Hi
    I install de JCo, But how i can call java class and methods from ABAP?. somebody has an example?
    The tutorial say that's is possible,  but don't explain how do that?
    Thanks.
    Angel G. Hurtado

    If you need only simple java program, you do not need to install JCo. The following codes can call java class.
    DATA: COMMAND TYPE STRING VALUE 'C:\j2sdk1.4.2_08\bin\java',
          DIR TYPE STRING VALUE D:\eclipse\workspace',
          PARAMETER TYPE STRING VALUE 'Helloworld'. "here the name of your java program
    CALL METHOD CL_GUI_FRONTEND_SERVICES=>EXECUTE
       EXPORTING
         APPLICATION = COMMAND
         PARAMETER = PARAMETER
         DEFAULT_DIRECTORY = DIR
       MAXIMIZED =
         MINIMIZED = 'X'     "If you need the DOS window to be minimized
      EXCEPTIONS
        CNTL_ERROR = 1
        ERROR_NO_GUI = 2
        BAD_PARAMETER = 3
        FILE_NOT_FOUND = 4
        PATH_NOT_FOUND = 5
        FILE_EXTENSION_UNKNOWN = 6
        ERROR_EXECUTE_FAILED = 7
        OTHERS = 8.
    Tell me if it works.
    Nuno.

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

Maybe you are looking for