Why use Java Beans?

Why should we use java beans?
Everybody says it is used to set the properties. What does this mean?
Can anyone give me a realtime scenario of the problems it can solve?
How does Spring framework utilize beans to solve problems? i.e wiring beans, declaring them in context file.

shalearns wrote:
Why should we use java beans?[http://java.sun.com/docs/books/tutorial/javabeans/index.html]
Everybody says it is used to set the properties. What does this mean?[http://java.sun.com/docs/books/tutorial/javabeans/whatis/index.html]
Can anyone give me a realtime scenario of the problems it can solve?[http://java.sun.com/docs/books/tutorial/javabeans/nb/index.html]
How does Spring framework utilize beans to solve problems? i.e wiring beans, declaring them in context file.[http://static.springframework.org/spring/docs/1.2.x/reference/beans.html]
~

Similar Messages

  • Search in form by using java bean or PJC.

    hi all
    i am confused because i do not know java bean to much,is it possible to create a search button with one text item in java bean to display all records
    example:
    if i enter dept 10 then it display all records related to dept 10?
    is it possible?
    if yes please cany anyone send me a demo?
    here is my email add.
    [email protected]
    sarah

    hi
    Francois thanks for the link and its very useful and i am studying the codes and also i downloaded demos and run them its working fine and its very very nice.
    i like java and trying to learn and its very useful.
    why i want to use java bean because one of my friend her name is sheela she wants me to do it but i am failed i did not do it in java bean
    so i thought lets try on the forum may be someone help u.
    so i posted a thread over here.
    thanks Francois.
    u r appreciated.once again thanks.
    sarah

  • Help : Unable to use Java Beans in Oracle forms 6i

    Hi ,
    I have been trying to run few sample code to understand how to use Java beans in oracle forms 6i .But have been largely unsuccessfull.
    It will be great if somebody can provide me with some simple form( and java code )which uses java beans concept to give some data to the java program and receive some data from it . Pls inform me about the settings that need to be done.
    If you guys know it then pls take the pains of writing a simple form and java code.
    i hope somebody will respond because your reply is very necesary for me to proceed.
    U can email me the code > [email protected]
    Thanks in advance.

    Thanks for your reply Francois.
    Actually i am not facing problem understanding the programming technique.
    I think the problem at my end is more of a cofiguration one.I am using forms version 6i
    on oracle 8.
    Every time i set the imlementation class property of the bean area it gives an error 13010 which translates to that "the class being mentioned is not extending the IView class".
    The class i have written extends VBean so i am not sure why this error is occuring.
    I think if oracle (correctly) finds the java class to use then i will be able to proceed.
    Pls reply.
    If you have some code that is working fine then pls send it to me.And also inform is some environment variables have to be set for its use.

  • Using java bean with jsp

    hello friends,
    i'm new to jsp. i want to create an html form that accepts username and a value from four radio buttons and display back the entered name and checked radio button's value using java bean.
    i use the <jsp:setProperty id="" property="*"> method. i don't know how to access the radio buttons value from the html.
    also when i use an additional field other than username the jsp page is showing error.
    Please give me the correct method to use java bean with jsp in this circumstance.
    thank you.

    thank you, but i have a problem left. the case is like this.
    i got the jsp and bean worked fine when i have a sinle input text field.
    but when i added a second text field i recieved the following error.
    javax.servlet.ServletException: basket.newbean.getUserPass()Ljava/lang/String;
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:825)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:758)
         org.apache.jsp.newform.process_jsp._jspService(process_jsp.java:69)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    where userPass is the new form element. I have made the subsequent chanes in my bean program and jsp file.
    pls hlp.

  • How to use Java Beans In JSTL?

    Hi
    I want to know how to use Java bean in JSTL
    please explain this with giving any one example.
    Thanks-
    Swapneel

    A bean is obtain by <jsp:useBean> tag nd once bean is obtained we can get its property by using getProperty tag.

  • How can I using java bean to insert new record

    Hi everybody,
    I'd some problem when I insert a record using java bean. When insert a record, the resultset executeUpdate return 0 anc cannot add record to database. Would you please tell me what's wrong in my code?
    java bean
    package miniproj;
    import java.sql.*;
    public class Register{
    private String sql;
    private String username;
    private String usertype;
    private String password;
    private String blocknum;
    private int floornum;
    private String owner;
    private int rows;
    private String s;
    // set parameter to database
    public int setMember(){
    try{
    //load database driver
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    // Get a connection to the database
    Connection sqlConn = java.sql.DriverManager.getConnection("jdbc.odbc:WFBS");
    // Get a statement from the connection
    Statement sqlStmt = sqlConn.createStatement();
    sql = "INSERT INTO USERS(user_name, password) VALEUS ('aaa', 'aaa')";
    // sql = "INSERT INTO USERS(user_name, password) VALEUS (" + user_name + "," + password + ")" ;
    rows = sqlStmt.executeUpdate(sql);
    // sqlRst.close();
    sqlStmt.close();
    sqlConn.close();
    catch(SQLException se){
    catch(Exception e){
    return rows;
    // set user name method
    public void setUsername(String name){
    username = name;
    // set passwrod method
    public void setPassword(String pwd){
    password = pwd;
    // set block num mehtod
    public void setBlockNum(String block){
    blocknum = block;
    // set floor num method
    public void setFloorNum(int floor){
    floornum = floor;
    // set owner method
    public void setOnwer(String own){
    owner = own;
    // get user name method
    public String getUsername(){
    return username;
    // get password method
    public String getPassword(){
    return password;
    jsp code
    <%@ include file="Header.jsp" %>
    <%@ page errorPage="Error.jsp" %>
    <jsp:useBean id="register" class="miniproj.Register" />
    <jsp:setProperty name="register" property="*" />
    User name : <%=register.getUsername()%><br>
    Password : <%=register.getPassword()%><br>
    <%
    int i = register.setMember();
    out.println(i);
    %>
    Thanks a lot
    Chris

    Seems to me that executeUpdate() would throw an SQLException, which in turn would get caught by your empty catch. The SQL keyword VALUES is misspelled. Put a 'se.printStackTrace()' in your catch to confirm this.

  • Value cannot refresh using Java bean

    When I use java bean to get a value. It suppose to refresh and show new value but it doesn't. So any code can help to resolve this issue.
    here is my code
    (Testing.jsp)
    <html>
    <head>
    <title>Page 3</title>
    <link rel=stylesheet type="text/css" href="auction.css">
    </head>
    <table class="mainBox" width="200">
    <tr><td class="boxTitle" >
    Testing number 3
    </td></tr>
    <tr><td>
    <span class="headline">
         <jsp:useBean id="testing2" class="com.jsp.newsys.testing.Testing2" scope="request">
         <jsp:setProperty name="testing2" property="user" value="Hello World"/>
    <jsp:getProperty name="testing2" property="user2"/>
         </jsp:useBean>
    </span>     
    </td></tr>
    </table>
    </html>
    The bean file which is Testing2.java
    package com.jsp.newsys.testing;
    import java.beans.*;
    import java.util.*;
    public class Testing2 extends Object implements java.io.Serializable {
         private String user;
         private String test;
    public Testing2() {
    public void setUser(String user)
              test="";
              if (user.equals("Hello World"))
                   test="Hi dqwqwd";
         public String getUser2()
         return this.test;
    I need to restart my tomcat everytime then only the value will refresh. Please help.
    Message was edited by:
    wesleygch
    Message was edited by:
    wesleygch
    Message was edited by:
    wesleygch

    Your bean maybe have misspelling error
    look at test and test2 on the jsp file. But I couldn't find any bean property test2 in your bean. Maybe you should try
    ${testing2.test} instead of ${testing2.test2}
    I am a new bie also....:-)

  • Upload to Excel using Java Bean

    Hi
    My requirement is that to upload the data to an excel sheet from a JTable(JTable is actually a java bean which gets its input from forms) and the user need to be given either to view the excel/save the excel/print the excel in any of the networked printers.
    Please cud someone help me with their inputs.
    Thanks again
    Deepa

    can you send me your code bean and form?
    I have example that i can send you to export to excel using webutil and OLE object.

  • Crystal Reports data connection using Java beans

    Hi
    My name is Bach Ong, i'm currently perform re-configuring Crystal reports 2008 to connect via
    Java bean to Jboss server, this uses look up service on JBoss server. The connection is using Connect
    look up using the properties:
    java.naming.provider.url=jnp://emgsydapp121:10499
    java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
    java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
    for file CRConfig.xml i put as follows:
    <JDBCURL></JDBCURL>
    <JDBCClassName></JDBCClassName>
    <JDBCUserName></JDBCUserName>
    <JNDIURL>jnp://emgsydapp121:10499</JNDIURL>
    <JNDIConnectionFactory>org.jnp.interfaces.NamingContextFactor
    y</JNDIConnectionFactory>
    <JNDIInitContext>/</JNDIInitContext>
    <JNDIUserName></JNDIUserName>
    Can you advise us if this step is correct, and is there any
    documentation that can guide us to right direction.
    for Java testing in Eclipse using remote call class it is working suing the following code:
            Properties p = new Properties();
            p.put(Context.INITIAL_CONTEXT_FACTORY,
            "org.jnp.interfaces.NamingContextFactory");
            p.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
            p.put(Context.PROVIDER_URL, "jnp://emgsydapp121:10499");
             InitialContext ctx = new InitialContext(p);
      Date asAtDate = CrystalUtils.convertToDate("2014-01-01", CrystalUtils.relativeToToday(0), false);
         String asxCode = "BHP";
         ClosingPricesReportRequest criteria = new ClosingPricesReportRequest(asAtDate, asxCode);
         InitialContext context = new InitialContext(p);
         ClosingPricesReportService ejb = (ClosingPricesReportService) context.lookup(ClosingPricesReportService.REMOTE_JNDI);
         ClosingPricesReport report = ejb.createMTMClosingPriceReport(criteria);
         System.out.println(report.getClosingPrices()[0].getClosingPrice());
         testval = report.getClosingPrices()[0].getClosingPrice().toString();
         System.out.println(testval);
    when i run the tes code the results as follow:
    10:49:45,244 DEBUG [SecurityAssociation ] Using ThreadLocal: false
    10:49:45,338 DEBUG [MicroSocketClientInvoker ] SocketClientInvoker[709446e4, socket://emgsydapp121:10473] constructed
    10:49:45,338 DEBUG [MicroRemoteClientInvoker ] SocketClientInvoker[709446e4, socket://emgsydapp121:10473] connecting
    10:49:45,338 DEBUG [MicroSocketClientInvoker ] Creating semaphore with size 50
    10:49:45,338 DEBUG [MicroRemoteClientInvoker ] SocketClientInvoker[709446e4, socket://emgsydapp121:10473] connected
    10:49:45,369 DEBUG [ClientSocketWrapper ] reset timeout: 0
    10:49:45,650 DEBUG [InvokerRegistry ] removed SocketClientInvoker[709446e4, socket://emgsydapp121:10473] from registry
    10:49:45,650 DEBUG [MicroSocketClientInvoker ] SocketClientInvoker[709446e4, socket://emgsydapp121:10473] disconnecting ...
    10:49:45,650 DEBUG [SocketWrapper ] ClientSocketWrapper[Socket[addr=/10.137.2.40,port=10473,localport=64150].2cba5bdb] closing
    37.99000000000000198951966012828052043914794921875
    37.99000000000000198951966012828052043914794921875
    Can anyone assist me in convert the above settings to get access by Crystal reports.
    My attemp current are below:
    public class CFDClosingPricesRpt extends CrystalReport {    
        //Constructor
        public CFDClosingPricesRpt(){
            super(ClosingPriceBean.INSTANCE);
         * Returns the ResultSet for this report to Crystal.
         * @param asxCode
         * @param asAtDateString
         * @return
    public ResultSet getNewReport(String asxCode, String asAtDateString) {                     
         try {
             Properties p = new Properties();
             p.put(Context.INITIAL_CONTEXT_FACTORY,
             "org.jnp.interfaces.NamingContextFactory");
             p.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
             p.put(Context.PROVIDER_URL, "jnp://emgsydapp121:10499");
             //InitialContext ctx = new InitialContext(p);
             clearCachedReportBeans();     
       Date asAtDate = CrystalUtils.convertToDate("2013-01-01", CrystalUtils.relativeToToday(0), false);
          asxCode = "BHP";
          ClosingPricesReportRequest criteria = new ClosingPricesReportRequest(asAtDate, asxCode);
          //ClosingPricesReportService ejb = (ClosingPricesReportService) ctx.lookup(ClosingPricesReportService.REMOTE_JNDI);
          ClosingPricesReportService ejb = (ClosingPricesReportService) ServiceLocator.getInstance().getService(ClosingPricesReportService.REMOTE_JNDI);           
          ClosingPricesReport report = ejb.createClosingPriceReport(criteria);
          // assemble Crystal-friendly DTO
          Collection closingPrices = Arrays.asList(report.getClosingPrices());
          for (Iterator iter = closingPrices.iterator(); iter.hasNext();) {
                    MBLXClosingPrice cp = (MBLXClosingPrice) iter.next();               
                    if (cp==null) continue;               
                    addReportBean(new ClosingPriceBean( report.getSuppliedDate(),
                                cp.getClosingPrice(),
                                cp.getAsxCode()));
      } catch (Throwable x) {     
          saveErrorMessage(x);
      return getAsResultSet();             
    Thanks
    Bach Ong

    Hi Don Thanks for the reply.
    I've was able to connect via Java beans and JNDI. But this one is going the JNDI of JBoss sever, which the JNDI already configure and working for Crystal reports v10.
    Bach

  • How to upload a file using java bean?

    hi,
    i need a code simple how to upload a file from jsp form to a java bean file (not a servlet)
    thank,s zik

    Hi,
    i need a code sample how to upload a file from jsp
    form to a java bean file (not a servlet)You can use jspSmartUpload component which is a free, fully-featured JSP component.
    jspSmartUpload provides you with all the upload/download features you could possibly wish for :
    * Simple and complete upload
    * Total control over the upload process
    * �Mixed forms� management
    * Total control over files sent
    * Download whatever you want
    For further information about jspSmartUpload please visit
    http://www.jspsmart.com/
    Hope this helps.
    Good Luck.
    Gayam.Srinivasa Reddy
    Developer Technical Support
    Sun Micro Sysytems
    http://www.sun.com/developers/support/

  • Using Java Bean in JSP to show database record

    I have links in my Tomcat container that if someone clicks on a specific link it should go to a Record page (Show.jsp) with all the values associated with a record from a database.
    For example if someone clicks on a specific link like this:
    LinkExample
    it would take you to a jsp with database info for someone named Jones and show you his info:
    Lastname = Jones
    Firstname = Mike
    City = San Diego
    I would like to do this using a Java helper class and bean so I dont have any database connection or Java code in my JSP.
    I created Java class file that has Database connection that works with a Java bean. I just dont know how to get the Show.jsp to work with the Java Bean and Java helper class file.
    Here is what I have for Show.jsp and this is the part I have been working on the longest but cant get it to work because it doesnt seem to work with the database:<jsp:useBean id="user" class="num.UserDB"/>
    //do I call getUser(lastname) here and if so how?
    <jsp:setProperty name="user" property="*"/>
    Last Name: <jsp:getProperty name="user" property="lastname"/><BR>
    First Name: <jsp:getProperty name="user" property="firstname"/><BR>
    City: <jsp:getProperty name="user" property="city"/><BR>My Java Helper class that compiles and connects to database:
    package num;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import num.User;
    public class UserDB
    public User getUser(String lastname)
    User user = new User();     
            try          
         Class.forName...//database connection stuff here
        ResultSet results = stmt.executeQuery("SELECT * from user where lastname = '" + lastname + "'");
         if(results.next() == true)
         results.next();
         user.setLastname(results.getString("lastname"));
         user.setFirstname(results.getString("firstname"));
            user.setFirstname(results.getString("city"));
         catch(Exception e)          
                   System.out.println("Exception...");               
       return user;
    }My Java Bean that compiles here:
    package num;
    public class User
      private String firstname;
      private String lastname;
    private String city;
      public User()
         //no arg constructor
      public User(String firstname, String lastname, String city)
           this.lastname = lastname;
              this.firstname = firstname;
              this.city = city;
      public String getLastname()
              return lastname;
      public void setLastname(String lastname)
         this.lastname = lastname;
      //more bean methods for all fields here
     

    Sorry if I wasnt specific enough. I have a link that passes a value (field that is passed is called lastname) to a JSP where I want to show record info for that value that is passed.
    My question is how do I show the database record info on Show.jsp for the lastname field value of Jones where I want to use a Java Bean and Database helper class in Show.jsp
    Here is the message I get when I hit the link (LinkExample) and it goes to Show.jsp:
    org.apache.jasper.JasperException: Cannot find any information on property 'lastname' in a bean of type 'num.UserDB'
    .....My UserDB class:
    public class UserDB
    public User getUser(String lastname)
    User user = new User();     
            try          
         Class.forName("org.gjt.mm.mysql.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/dbconnone?user=smitherson&password=abcdefg");
        Statement stmt = conn.createStatement();
        ResultSet results = stmt.executeQuery("SELECT * from user where lastname = '" + lastname + "'");
         if(results.next() == true)
         results.next();
         user.setLastname(results.getString("lastname"));
         user.setFirstname(results.getString("firstname"));
                         user.city(results.getString("city"));
         catch(Exception e)          
             System.out.println("Exception..." + e);          
       return user;
    }Bean class:
    package num;
    public class User
      private String firstname;
      private String lastname;
      private String city;
      public User()
         //no arg constructor
      public User(String firstname, String lastname, Sting city)
          this.firstname = firstname;
           this.lastname = lastname;
    this.city = city;
      public String getFirstname()
              return firstname;
      public void setFirstname(String firstname)
         this.firstname = firstname;
      public String getLastname()
              return lastname;
      public void setLastname(String lastname)
         this.lastname = lastname;
      public String getCity()
              return city;
      public void setCity(String city)
         this.city = city;
      

  • Using Java Beans in Java Server Pages

    Can we not use a method of Java Bean in a Java Server Page ?
    I am trying to retrieve the user email from a java bean method "getUserEmail". I am instantiating the class, but when I try to use that in JSP tags, I am getting an error.
    <jsp:useBean class = "formjavabean.application" id = "applicationId" scope = "session" />
    <%@ page import="java.io.*, java.lang.*" %>
    <%!
    String user = applicationId.getUserEmail() ;
    String f3 = "ftn03" ;
    String f3not = "ftn03 file not uploaded";
    ...........I am failing in debugging that, can anyone help plz ?

    Here is my whole code in parts:
    First the head section:
    <head>
    <title> Fastran </title>
    <jsp:useBean class = "formjavabean.application" id = "applicationId" scope = "session" />
    </head>JSP part in the body section :
    <%@ page import="java.lang.*, java.io.*" %>
    <%!
    private String f3 = "ftn03";
    private String f3not = "ftn03 file not uploaded";
    private String f7 = "ftn07";
    private String f7not = "ftn07 file not uploaded";
    private String f9 = "ftn09";
    private String f9not = "ftn09 file not uploaded";
    public String checkFile3()
        File ch3 = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\ftn03") ;
        if (ch3.exists() == true)
            return f3 ;
        else
            return f3not ;
    public String checkFile7()
        File ch7 = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\ftn07") ;
        if (ch7.exists() == true)
            return f7 ;
        else
            return f7not ;
    public String checkFile9()
        File ch9 = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\ftn09") ;
        if (ch9.exists() == true)
            return f9 ;
        else
            return f9not ;
    %>Java Script in the body section, using methods defined in the JSP part:
    <script type="text/javascript">
            function validate_file ( )
                    var file3 = "<%= checkFile3() %>" ;
                    var file7 = "<%= checkFile7() %>" ;
                    var file9 = "<%= checkFile9() %>" ;
                    if ( file3 != "ftn03" || file7 != "ftn07" || file9 != "ftn09" )
                        alert("Please upload the required file") ;   
                        return ("fastran.jsp") ;
                    else
                        return ("processForm.jsp") ;
            function validate_upload ( )
                    valid = true;
                    if ( document.val_file.filefield.value == "")
                            alert("Please select a file for upload") ;
                            valid = false;
                    return valid;
        </script>Finally the form and button part of the page, in the body section:
    <form name = "val_file" method="post" action="upload.jsp" name="submit" enctype="multipart/form-data" onSubmit = "return validate_upload();">
    Upload Files: <input type="file" name="filefield" >&nbsp&nbsp<input type="submit" name="submit" value="Upload"><br>
    <font color = "Red"><h5>(ftn03,ftn07, and ftn09)</h5></font><br><br><br>
    Files on the server :<br><br>
    <font color = "Green"><h5>
    <%= checkFile3() %><br>
    <%= checkFile7() %><br>
    <%= checkFile9() %><br>
    </h5></font>
    <br><br><br><br><br><br><br><br><br>
    <input type=button onClick="location.href='logintest.jsp'" value='Home'>  <input type=button onClick="location.href=validate_file()" value='Proceed' ><br>
    </form>Now try this:
    Change <%! to <%, or try using bean method as:
    String userEmail = applicationId.getUserEmail() ;..........and that is my problem. I would really appreciate any help, thanks

  • Using java beans in jsp using tomcat

    hi i have made a form to enter user first name and last anme with html and then i have made a value javabean in which i want to store the information filled bu user. i want to display the information stored in java bean in jsp page i have made the full application and i have made class file of java bean as well as jsp file but when i try to run this web application in tomcat i am getting class not found exception.
    could anybody tell me that where i should store the bean class in tomcat and do i need to make any package in which i have to place my java bean file plz tell me complete procedure along with code if possible

    whew thats a lot of questions... All of this is pretty basic stuff. I would recommend you take a look at the web services tutorial: http://java.sun.com/j2ee/1.4/docs/tutorial/doc/
    lets see.
    Starting a package name with com is just a generic standard which is followed.
    It is most correct when creating commercial packages to create packages like com.companyName.project
    http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html
    You should not need a page import directive unless you are using classes in scriptlets: ie <% %> tags in your JSP. Your jsp:useBean tag will automatically import necessary classes - you don't need to import classes for beans specifically
    <jsp:useBean id="myClass" scope="session" class="com.myPackage" />
    Your directory structure should be something like this
    webApplicationRootDirectory
    - page1.html
    - page2.html
    - page3.jsp
    - page4.jsp
    - WEB-INF
         - web.xml
         - classes
           - com
             - myPackage
               - myClass.classerrrm. Thats about it I think.

  • Database access design using java bean

    Hi,
    I am writing a JSP/servlet/Javabean based app. using MVC architecture.The database related logic is in java beans.
    I want a generalized class/bean that can form a connection , execute the passed query and return the results.Does any one has any URLs or sample code to explain how to do this using introspection?
    I would greatly appreciate any help as this design is very crucial for our application.
    Thanks -
    k

    Please check the Cameleon Open Source project at http://www.must.de/cameleon.html if ti fits your needs.

  • Using java.beans.EventHandler to create javafx.event.EventHandler instances

    One thing I do not like about the JavaFX EventHandler is all the anonymous classes that need to be created. This messes up the way the code looks and I heard that creating all these anonymous classes adds to the total number of classes that get loaded.
    In searching for a way around this I found java.beans.EventHandler's create method. This method (there are a few variations of it) its suppose to provide a one liner to create anonymous implementations of listener interfaces (like JavaFX's EventHandler). So I decided to try it out against some of the sample JavaFX code that is out there.
    I used.... http://docs.oracle.com/javafx/2.0/events/KeyboardExample.java.htm... as my test code.
    I replaced...
            private void installEventHandler(final Node keyNode) {
                // handler for enter key press / release events, other keys are
                // handled by the parent (keyboard) node handler
                final EventHandler keyEventHandler = new EventHandler<KeyEvent>() {
                    @Override
                    public void handle(final KeyEvent keyEvent) {
                        if (keyEvent.getCode() == KeyCode.ENTER) {
                            setPressed(keyEvent.getEventType() == KeyEvent.KEY_PRESSED);
                            keyEvent.consume();
                keyNode.setOnKeyPressed(keyEventHandler);
                keyNode.setOnKeyReleased(keyEventHandler);
            }with....
            private void installEventHandler(final Node keyNode) {
                // handler for enter key press / release events, other keys are
                // handled by the parent (keyboard) node handler
                final EventHandler keyEventHandler = (EventHandler)java.beans.EventHandler.create(EventHandler.class, this, "handle", "");
                keyNode.setOnKeyPressed(keyEventHandler);
                keyNode.setOnKeyReleased(keyEventHandler);
    public void handle(final KeyEvent keyEvent) {
                if (keyEvent.getCode() == KeyCode.ENTER) {
                    setPressed(keyEvent.getEventType() == KeyEvent.KEY_PRESSED);
                    keyEvent.consume();
            }It worked. The new code behaved just like the old code.
    One caveat though. The class count did in fact go up by about 20 classes. I ran multiple runs and this was true for all of them. But I only applied this technique on one anonymous class. It could be the case that the real savings in class count come after many instances of swapping out anonymous classes with this technique.
    From the javadoc
    "Also, using EventHandler in large applications in which the same interface is implemented many times can reduce the disk and memory footprint of the application.
    The reason that listeners created with EventHandler have such a small footprint is that the Proxy class, on which the EventHandler relies, shares implementations of identical interfaces. For example, if you use the EventHandler create methods to make all the ActionListeners in an application, all the action listeners will be instances of a single class (one created by the Proxy class). In general, listeners based on the Proxy class require one listener class to be created per listener type (interface), whereas the inner class approach requires one class to be created per listener (object that implements the interface)."
    Edited by: jmart on Apr 23, 2012 2:13 AM

    Well, the idea is that with Java 8 they can be rewritten to something like this:
    private void installEventHandler(final Node keyNode) {
                // handler for enter key press / release events, other keys are
                // handled by the parent (keyboard) node handler
                EventHandler keyEventHandler = keyEvent => {
                        if (keyEvent.getCode() == KeyCode.ENTER) {
                            setPressed(keyEvent.getEventType() == KeyEvent.KEY_PRESSED);
                            keyEvent.consume();
                keyNode.setOnKeyPressed(keyEventHandler);
                keyNode.setOnKeyReleased(keyEventHandler);
            }Basically what you are doing now is sacrificing performance (both in real performance and in a lot of extra garbage created) for a little bit of memory gain. Unless you have good reasons and measurements to back this up I think this would definitely qualify as premature optimization.
    I'm a heavy user of anonymous inner classes myself, having several hundreds of them now in my project and I have yet to run into problems. I often write code like the example below purely for readability and convience:
    Set<String> someSet = new HashSet<>() {{
      add("A");
      add("B");
    new HBox() {{
      getChildren.add(new VBox() {{
        getChildren.add(new Label("Hi"));
      getChildren.add(new VBox() {{
        getChildren.add(new Label("There"));
    }};

Maybe you are looking for