Static methods in JNDI ObjectFactory

I am trying to solve a simple problem, in what is turning out to be a slightly convoluted way. I take the convolutions to be a warning sign that I may be trying to do something illicit (from a Java EE standpoint). What I would like to know is whether there is anything seriously wrong with the approach I am taking here.
I would like to be able to assign a "ticket number" to long-running asynchronous background tasks (initiated by JMS messages and processed by MDBs), which can be used to check on the status of a task.
Each MDB receives the ticket number as part of the message that initializes it, and while running periodically calls a method on a TaskMonitor object, referencing the ticket number, to update its status. Clients calling Session Bean methods can discover what the current progress of a task is by obtaining the TaskMonitor object and requesting information using the same ticket number. This way we can do things like display a progress bar in an Ajax client (for example).
The TaskMonitor object is a simple in-memory hashtable of ticket numbers and status/progress indicators. It is registered as a custom resource via JNDI: both task-processing MDBs and clients wanting to check up on the status of a task must obtain the TaskMonitor object instance via a JNDI lookup.
In order to make sure that it is always the same TaskMonitor object that is obtained by boths tasks and clients requesting it via JNDI (and thus that ticket numbers and status numbers are global within the system), I therefore have a static instance of the TaskMonitor class cached in the ObjectFactory that creates TaskMonitors when one is requested via JNDI. But will this really work? What happens in a clustered environment, for example - will different nodes in the cluster in practice have different ObjectFactory instances, each with its own separate static instance of the TaskMonitor?
What I'm trying to avoid here is having to persist essentially transient information about task progress to a database. An in-memory hashtable, shared by all tasks and all clients, is fine for my purposes. I also don't want my MDBs to report back on their status via JMS, because I want clients to be able to obtain that status on demand rather than poll for update messages. But is the way I've opted for architecturally kosher?

Java EE doesn't really make guarantees about what should happen in clusters.
But it does sound to me that either you should use an entity bean (and hence a database which you're trying to avoid) or look at some caching technology which provides this semantic - Tangosol is one, but it's not free.

Similar Messages

  • Static methods in data access classes

    Are we getting any advantage by keeping functions of DAOs (to be accessed by Session Beans) static ?

    I prefer to have a class of static methods that
    require a Connection to do their work. Usually, there
    is a SessionBean that 'wraps' this DAO. The method
    signatures for the SSB are the same, minus the need
    for a Connection, which the SSB gets before delegating
    to the Static Class.Uggh, passing around a connection. I've had to refactor a bunch of code that used this pattern. We had classes in our system that took a class in their constructor simply because one of their methods created an object that needed the connection. Bad news--maintenance nightmare--highly inflexible.
    What we've done is create ConnectionFactory singletons that are used throughtout the application in order to get connections to the database. All connection factory implementations implement the same interface so they can be plugged in from other components at runtime.
    In my opinion, classes that use connections should manage them themselves to ensure proper cleanup and consistent state. By using a factory implementation, we simply provide the DAO classes the means by which they can retrieve connections to the database and even the name of the database that needs to be used that is pluggable. The DAO classes do their own connection management.
    For similar reasons, I eschew the static method concept. By using class methods, you make it difficult to plug in a new implementation at runtime. I much prefer the singleton pattern with an instance that implements a common interface instead of a class full of static methods.
    I recently needed to dynamically plug in new connection factory implementation so that we could use JNDI and DataSources within the context of the application server (pooled connections) but use direct connections via the Driver manager for unit testing (so the application server didn't need to be running). Because of the way this was coded, I simply changed the original factory to be an abstract factory and changed the getInstance() method to return a different implementation based on the environment (unit test vs live). This was painless and didn't require changing a single line of client code.
    If I had to do this using the previous code that I refactored, I would have had to change about 200 jsp pages and dozens of classes that were making calls to the static method of the previous factory or hacked in something ugly and hard to maintain.
    YMMV

  • Static methods in concurrency

    I have a static method which takes a few String and double parameters and contains only local variables. When it is called by multiple threads there seems to be an exception thrown intermittenly. I got a little paranoid and so I've changed it to an instance method, and now the problem seems to disappear.
    Is this just a coincidence? Is my static method intrinsically thread-safe? Or are there any concurrency issues with static methods that I'm not aware of?
    Any reply is much appreciated!

    public static net.opengis.sos.v_1_0_0.InsertObservationResponse insertObservation(String serverURL, String AssignedSensorId, String dataType, String timeFrom, String timeTo, String srsName, double x, double y, long numElement, String dataString) throws MalformedURLException, IOException, JAXBException, ParserConfigurationException {
            OutputStream out = null;
            InputStream in = null;
            try {
                URL url = new URL(serverURL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-type", "text/xml, application/xml");
                out = connection.getOutputStream();
                JAXBContext jaxbContext = JAXBContext.newInstance("net.opengis.sos.v_1_0_0:net.opengis.ows.v_1_1_0:net.opengis.sos.v_1_0_0.filter.v_1_1_0:net.opengis.sensorml.v_1_0_1:net.opengis.swe.v_1_0_1:net.opengis.om.v_1_0_0:net.opengis.gml.v_3_1_1:net.opengis.sampling.v_1_0_0");
                /////////////////////////////////request
                Marshaller marshaller = jaxbContext.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                //////////////////////////////////////object factories
                net.opengis.gml.v_3_1_1.ObjectFactory gmlOF = new net.opengis.gml.v_3_1_1.ObjectFactory();
                net.opengis.swe.v_1_0_1.ObjectFactory sweOF = new net.opengis.swe.v_1_0_1.ObjectFactory();
                net.opengis.sampling.v_1_0_0.ObjectFactory saOF = new net.opengis.sampling.v_1_0_0.ObjectFactory();
                ////////////////////////////////////////////////////////////////////////////////////////////////getObservation request
                net.opengis.sos.v_1_0_0.InsertObservation insertObservation = new net.opengis.sos.v_1_0_0.InsertObservation();
                insertObservation.setAssignedSensorId(AssignedSensorId);
                net.opengis.om.v_1_0_0.ObservationType observation = new net.opengis.om.v_1_0_0.ObservationType();
                ///////////////////////////////om:samplingTime
                //begin position
                net.opengis.gml.v_3_1_1.TimePositionType beginTimePosition = new net.opengis.gml.v_3_1_1.TimePositionType();
                beginTimePosition.getValue().add(timeFrom);
                //end position
                net.opengis.gml.v_3_1_1.TimePositionType endTimePosition = new net.opengis.gml.v_3_1_1.TimePositionType();
                endTimePosition.getValue().add(timeTo);
                //time period
                net.opengis.gml.v_3_1_1.TimePeriodType timePeriod = new net.opengis.gml.v_3_1_1.TimePeriodType();
                timePeriod.setBeginPosition(beginTimePosition);
                timePeriod.setEndPosition(endTimePosition);
                net.opengis.swe.v_1_0_1.TimeObjectPropertyType timeObjectPropertyType = new net.opengis.swe.v_1_0_1.TimeObjectPropertyType();
                timeObjectPropertyType.setTimeObject(gmlOF.createTimePeriod(timePeriod));
    //            timeObjectPropertyType.setTimeObject(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.TimePeriodType.class, timePeriod));
                observation.setSamplingTime(timeObjectPropertyType);
                /////////////////////////////////om:procedure
                net.opengis.om.v_1_0_0.ProcessPropertyType processPropertyType = new net.opengis.om.v_1_0_0.ProcessPropertyType();
                processPropertyType.setHref(AssignedSensorId);
                observation.setProcedure(processPropertyType);
                /////////////////////////////////om:observedProperty
                net.opengis.swe.v_1_0_1.CompositePhenomenonType compositePhenomenonType = new net.opengis.swe.v_1_0_1.CompositePhenomenonType();
                compositePhenomenonType.setId("cpid0");
                compositePhenomenonType.setDimension(BigInteger.ONE);
                net.opengis.gml.v_3_1_1.CodeType codeType = new net.opengis.gml.v_3_1_1.CodeType();
                codeType.setValue("resultComponents");
                compositePhenomenonType.getName().add(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.CodeType.class, codeType));
                net.opengis.swe.v_1_0_1.PhenomenonPropertyType phenomenonPropertyType1 = new net.opengis.swe.v_1_0_1.PhenomenonPropertyType();
                phenomenonPropertyType1.setHref("urn:ogc:data:time:iso8601");
                compositePhenomenonType.getComponent().add(phenomenonPropertyType1);
                net.opengis.swe.v_1_0_1.PhenomenonPropertyType phenomenonPropertyType2 = new net.opengis.swe.v_1_0_1.PhenomenonPropertyType();
                phenomenonPropertyType2.setHref("Abfluss");
                compositePhenomenonType.getComponent().add(phenomenonPropertyType2);
                net.opengis.swe.v_1_0_1.PhenomenonPropertyType observedProperty = new net.opengis.swe.v_1_0_1.PhenomenonPropertyType();
                observedProperty.setPhenomenon(sweOF.createCompositePhenomenon(compositePhenomenonType));
                observation.setObservedProperty(observedProperty);
                ////////////////////////////////om:featureOfInterest
                net.opengis.sampling.v_1_0_0.SamplingPointType samplingPoint = new net.opengis.sampling.v_1_0_0.SamplingPointType();
                samplingPoint.setId(AssignedSensorId);
                net.opengis.gml.v_3_1_1.CodeType saName = new net.opengis.gml.v_3_1_1.CodeType();
                saName.setValue(AssignedSensorId);
                samplingPoint.getName().add(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.CodeType.class, saName));
                //samplingPoint.getSampledFeature().add(gmlOF.createFeaturePropertyType());
                net.opengis.gml.v_3_1_1.DirectPositionType pos = new net.opengis.gml.v_3_1_1.DirectPositionType();
                pos.setSrsName(srsName/*"urn:ogc:def:crs:EPSG:4326"*/);
                pos.getValue().add(x);
                pos.getValue().add(y);
                net.opengis.gml.v_3_1_1.PointType point = new net.opengis.gml.v_3_1_1.PointType();
                point.setPos(pos);
                net.opengis.gml.v_3_1_1.PointPropertyType pointProperty = new net.opengis.gml.v_3_1_1.PointPropertyType();
                pointProperty.setPoint(point);
                samplingPoint.setPosition(pointProperty);
                net.opengis.gml.v_3_1_1.FeaturePropertyType featureMember = new net.opengis.gml.v_3_1_1.FeaturePropertyType();
                featureMember.setFeature(saOF.createSamplingPoint(samplingPoint));
                net.opengis.gml.v_3_1_1.FeatureCollectionType featureCollectionType = new net.opengis.gml.v_3_1_1.FeatureCollectionType();
                featureCollectionType.getFeatureMember().add(featureMember);
                net.opengis.gml.v_3_1_1.FeaturePropertyType featureOfInterest = new net.opengis.gml.v_3_1_1.FeaturePropertyType();
                featureOfInterest.setFeature(gmlOF.createFeatureCollection(featureCollectionType));
    //            featureOfInterest.setFeature(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.FeatureCollectionType.class, featureCollectionType));
                observation.setFeatureOfInterest(featureOfInterest);
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.newDocument();
                final String sweNS = "http://www.opengis.net/swe/1.0.1";
                Element dataArray = doc.createElementNS(sweNS, "swe:DataArray");
                Element elementCount = doc.createElementNS(sweNS, "swe:elementCount");
                Element count = doc.createElementNS(sweNS, "swe:Count");
                Element value = doc.createElementNS(sweNS, "swe:value");
                dataArray.appendChild(elementCount).appendChild(count).appendChild(value).appendChild(doc.createTextNode(String.valueOf(numElement)));
                Element elementType = doc.createElementNS(sweNS, "swe:elementType");
                elementType.setAttribute("name", "Components");
                Element simpleDataRecord = doc.createElementNS(sweNS, "swe:SimpleDataRecord");
                Element timeField = doc.createElementNS(sweNS, "swe:field");
                timeField.setAttribute("name", "Time");
                Element time = doc.createElementNS(sweNS, "swe:Time");
                time.setAttribute("definition", "urn:ogc:data:time:iso8601");
                Element featureField = doc.createElementNS(sweNS, "swe:field");
                featureField.setAttribute("name", "feature");
                Element text = doc.createElementNS(sweNS, "swe:Text");
                text.setAttribute("definition", "urn:ogc:data:feature");
                Element dataField = doc.createElementNS(sweNS, "swe:field");
                dataField.setAttribute("name", dataType);
                Element quantity = doc.createElementNS(sweNS, "swe:Quantity");
                quantity.setAttribute("definition", dataType);
                Element uom = doc.createElementNS(sweNS, "swe:uom");
                uom.setAttribute("code", "m3 per s");
                simpleDataRecord.appendChild(timeField).appendChild(time);
                simpleDataRecord.appendChild(featureField).appendChild(text);
                simpleDataRecord.appendChild(dataField).appendChild(quantity).appendChild(uom);
                dataArray.appendChild(elementType).appendChild(simpleDataRecord);
                Element encoding = doc.createElementNS(sweNS, "swe:encoding");
                Element textBlock = doc.createElementNS(sweNS, "swe:TextBlock");
                textBlock.setAttribute("decimalSeparator", ".");
                textBlock.setAttribute("tokenSeparator", ",");
                textBlock.setAttribute("blockSeparator", ";");
                dataArray.appendChild(encoding).appendChild(textBlock);
                Element sweValues = doc.createElementNS(sweNS, "swe:values");
                dataArray.appendChild(sweValues).appendChild((doc.createTextNode(dataString)));
                Element result = doc.createElementNS("http://www.opengis.net/om/1.0", "om:result");
                result.appendChild(dataArray);
                observation.setResult(result);
                insertObservation.setObservation(observation);
                //handle "ogc" namespace bug
                NamespacePrefixMapper mapper = new PreferredMapper();
                marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);
                marshaller.marshal(insertObservation, System.out);
                marshaller.marshal(insertObservation, out);
                Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                in = connection.getInputStream();
                Object response = unmarshaller.unmarshal(new StreamSource(in));
                if (response instanceof net.opengis.sos.v_1_0_0.InsertObservationResponse) {
                    return (net.opengis.sos.v_1_0_0.InsertObservationResponse) response;
                } else if (response instanceof net.opengis.ows.v_1_1_0.ExceptionReport) {
                    net.opengis.ows.v_1_1_0.ExceptionReport exceptionReport = (net.opengis.ows.v_1_1_0.ExceptionReport) response;
                    StringBuilder strBuilder = new StringBuilder();
                    for (net.opengis.ows.v_1_1_0.ExceptionType ex : exceptionReport.getException()) {
                        StringBuilder tempBuilder = new StringBuilder(ex.getExceptionCode() + ": ");
                        for (String temp : exceptionReport.getException().get(0).getExceptionText()) {
                            tempBuilder.append(temp + "\n");
                        strBuilder.append(tempBuilder.toString() + "\n");
                    throw new IllegalArgumentException(strBuilder.toString());
                } else {
                    throw new IllegalStateException("Unrecognizeable response type!");
            } finally {
                if (out != null) {
                    out.close();
                if (in != null) {
                    in.close();
        }Edited by: 808239 on 10-Feb-2011 02:44

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • Using a non-static vector in a generic class with static methods

    I have a little problem with a class (the code is shown underneath). The problem is the Assign method. This method should return a clone (an exact copy) of the set given as an argument. When making a new instance of a GenericSet (with the Initialize method) within the Assign method, the variables of the original set and the clone have both a reference to the same vector, while there exists two instances of GenericSet. My question is how to refer the clone GenericSet's argument to a new vector instead of the existing vector of the original GenericSet. I hope you can help me. Thanks
    package genericset;
    import java.util.*;
    public class GenericSet<E>{
    private Vector v;
    public GenericSet(Vector vec) {
    v = vec;
    private <T extends Comparable> Item<T> get(int index) {
    return (Item<T>) v.get(index);
    public static <T extends Comparable> GenericSet<T> initialize() {
    return new GenericSet<T>(new Vector());
    public Vector getVector() {
    return v;
    public static <T extends Comparable> GenericSet<T> insert (GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (!member(g,i))
    v.addElement(i);
    return g;
    public static <T extends Comparable> GenericSet<T> delete(GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (member(g,i))
    v.remove(i);
    return g;
    public static <T extends Comparable> boolean member(GenericSet<T> z, Item<T> i) {
    Vector v = z.getVector();
    return v.contains(i);
    public static <T extends Comparable> boolean equal(GenericSet<T> z1, GenericSet<T> z2) {
    Vector v1 = z1.getVector();
    Vector v2 = z2.getVector();
    if((v1 == null) && (v2 != null))
    return false;
    return v1.equals(v2);
    public static <T extends Comparable> boolean empty(GenericSet<T> z) {
    return (cardinality(z) == 0);
    public static <T extends Comparable> GenericSet<T> union(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = assign(z1);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> intersection(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> difference(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    insert(g, elem);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(!member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> assign(GenericSet<T> z) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z); i++) {
    Item<T> elem = z.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> boolean subset(GenericSet<T> z1, GenericSet<T> z2) {
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    return false;
    return true;
    public static <T extends Comparable> int cardinality(GenericSet<T> z){
    Vector v = z.getVector();
    return v.size();
    }

    The issue is not "reference a non-static interface", but simply that you cannot reference a non-static field in a static method - what value of the field ed would the static method use? Seems to me your findEditorData should look something like this:   public static EditorBean findEditorData( String username, EditorBean editorData )
          return editorData.ed.findEditor( username );
       }

  • Using HttpServletRequest object to share variables between static methods.

    Does anyone know of the overhead/performance implications of using the HttpServletRequest object to share variables between a static method and the calling code?
    First, let me explain why I am doing it.
    I have some pagination code that I would like to share across multiple servlets. So I pulled the pagination code out, and created a static method that these servlets could all use for their pagination.
    public class Pagination {
         public static void setPagination (HttpServletRequest request, Config conf, int totalRows) {
              int page = 0;
              if (request.getParameter("page") != null) {
                   page = new Integer(request.getParameter("page")).intValue();
              int articlesPerPage = conf.getArticlesPerPage();
              int pageBoundary = conf.getPageBoundary();
                int numOfPages = totalRows / articlesPerPage;  
                // Checks if the page variable is empty (not set)
                if (page == 0 || (page > numOfPages && (totalRows % articlesPerPage) == 0 && page < numOfPages + 1)) {    
                 page = 1;  // If it is empty, we're on page 1
              // Ex: (2 * 25) - 25 = 25 <- data starts at 25
             int startRow = page * articlesPerPage - (articlesPerPage);
             int endRow = startRow + (articlesPerPage);           
             // Set array of page numbers.
             int minDisplayPage = page - pageBoundary;
             if (minDisplayPage < 1) {
                  minDisplayPage = 1;     
             int maxDisplayPage = page + pageBoundary;
             if (maxDisplayPage > numOfPages) {
                  maxDisplayPage = numOfPages;     
             int arraySize = (maxDisplayPage - minDisplayPage) + 1;
             // Check if there is a remainder page (partially filled page).
             if ((totalRows % articlesPerPage) != 0) arraySize++;
             // Set array to correct size.
             int[] pages = new int[arraySize];
             // Fill the array.
             for (int i = 1; i <= pages.length; i++) {
                  pages[i - 1] = i;
             // Set pageNext and pagePrev variables.
             if (page != 1) {
                  int pagePrev = page - 1;
                  request.setAttribute("pagePrev", pagePrev);
             if ((totalRows - (articlesPerPage * page)) > 0) {
                 int pageNext = page + 1;
                 request.setAttribute("pageNext", pageNext);
             // These will be used by calling code for SQL query.
             request.setAttribute("startRow", startRow);
             request.setAttribute("endRow", endRow);
             // These will be used in JSP page.
             request.setAttribute("totalRows", totalRows);
             request.setAttribute("numOfPages", numOfPages);
             request.setAttribute("page", page);
             request.setAttribute("pages", pages);          
    }I need two parameters from this method (startrow and endrow) so I can perform my SQL queries. Since this is a multithreaded app, I do not want to use class variables that I will later retrieve through methods.
    So my solution was to just set the two parameters in the request and grab them later with the calling code like this:
    // Set pagination
    Pagination.setPagination(request, conf, tl.getTotalRows());
    // Grab variables set into request by static method
    int startRow = new Integer(request.getAttribute("startRow").toString());
    int endRow = new Integer(request.getAttribute("endRow").toString());
    // Use startRow and endRow for SQL query below...Does anyone see any problem with this from a resource/performance standpoint? Any idea on what the overhead is in using the HttpServletRequest object like this to pass variables around?
    Thanks for any thoughts.

    You could either
    - create instance vars in both controllers and set them accordingly to point to the same object (from the App Delegate) OR
    - create an instance variable on the App Delegate and access it from within the view controllers
    Hope this helps!

  • Can you set a global EntityResolver (via system property, or static method)

    I'm trying to set a customized EntityResolver (telling the xml parser where to look for XML schema files).
    Usually, you'd use the standard syntax - somehting like:
    SaxParser parser=new SaxParser();
    parser.parser.setEntityResolver(myResolver);
    However, I was wondering whether you can set a "global" EntityResolver, to be used as default for all parsers ?
    Maybe this can be done through some system property, or a static method somewhere in the parsing XML ?
    (BTW, I need it because I'm using some third-party API, that encapsulates a SaxParser, but won't let me access it, so I can't configure it directly).
    thanks.

    I don't think you can.
    What is possible is to set content on the folder resource itself; that would be returned instead of the page you mentioned.

  • How to call a static method from an event handler

    Hi,
       I'm trying to call a static method of class I designed.  But I don't know how to do it.  This method will be called from an event handler of a web dynpro for Abap application.
    Can somebody help me?
    Thx in advance.
    Hamza.

    To clearly specify the problem.
    I have a big part code that I use many times in my applications. So I decided to put it in a static method to reuse the code.  but my method calls functions module of HR module.  but just after the declaration ( at the first line of the call function) it thows an exception.  So I can't call my method.

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Calling a method from a static method

    hello all,
    I'm calling a non-static method from a static method (from the main method). To overcome this i can make the method i am calling static but is there another way to get this to work without making the method that is being called static?
    all replies welcome, thanks

    When you call a non-static method, you are saying you are calling a method on an object. The object is an instance of the class in which the method is defined. It is a non-static method, because the instance holds data in it's instance variables that is needed to perform the method. Therefore to call this kind of method, you need to get (or create an instance of the class. Assuming the two methods are in the same class, you could do
    public class Foo
         public static void main(String[] args)
                Foo f = new Foo();
                f.callNonStaticMethod();
    }for instance.

  • Calling a non-static method from another Class

    Hello forum experts:
    Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
    1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
        populates a JTable.
    2. User selects a row in the table and then clicks a button on the icon toolbar
        which is part of UIMenu class.
    3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
    (a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
                                      == OR ==
    (b). I could declare UpdateDatabase() as static and call this method without
         creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
    object specific data.
    With option (b), if I declare the method as static, the variables used in the method would also have to be static.
    The variables, in which case, would not be object specific.
    Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
    object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
    way?
    Any ideas or thoughts will be of tremendous help. Thanks in advance.

    Hello Forum:
    Danny_From_Tower, Encephalatic: Thank you both for your responses.
    Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
    and declared as public.
    public class MyMenu {
        public JButton btnAccept;
         //Constructor
         public MyMenu()     {
              btnAccept = new JButton("Accept");
    }     I instantiate an object for MyMenu class in the main application class MyApp.
    public class MyApp {
         private     MyMenu menu;
         //Constructor     
         public MyApp(){
              menu = new MyMenu();     
         public void openOrder(){
               MyGUI MyIntFrame = new MyGUI(menu.btnAccept);          
    }I pass this button all the way down to the class detail02. Now I want to set up a listener for this
    button in the class detail02. I am not able to do this.
    public class MyGUI {
         private JButton acceptButton;
         private detail02 dtl1 = new detail02(acceptButton);
         //Constructor
         public AppGUI(JButton iButton){
         acceptButton = iButton;
    public class detail02{
        private JButton acceptButton;
        //Constructor
        public detail02(JButton iButton){
          acceptButton = iButton;
          acceptButton.addActionListener(new acceptListener());               
       //method
        private void acceptListener_actionPerformed(ActionEvent e){
           System.out.println("Menu item [" + e.getActionCommand(  ) + "] was pressed.");
        class acceptListener implements ActionListener {       
            public void actionPerformed(ActionEvent e) {
                   acceptListener_actionPerformed(e);
    }  I am not able to get the button Listener to work. I get NullPointerException at this line
              acceptButton.addActionListener(new acceptListener());in the class detail02.
    Is this the right way? Or is there a better way of accomplishing my objective?
    Please help. Your inputs are precious! Thank you very much for your time!

  • Calling a static method from another class

    public class Command
        public static void sortCommands(String command, String order, List object)
             if(command.equalsIgnoreCase("merge") && order == "a")
                  object.setAscending(true);
                  Mergesort.mergesort(object.list);                  // line 85
    }and
    public class Mergesort
         public static void mergesort (int[] a)
              mergesort(a, 0, a.length-1);
         private static void mergesort (int[] a, int l, int r)
         private static void merge (int[] a, int l, int m, int r)
    }Error:
    Command.java:85: cannot find symbol
    symbol : variable Mergesort
    location: class Command
    Mergesort.mergesort(object.list)
    What am I doing wrong here? Within the Command class I am calling mergesort(), a static method, from a static method. I use the dot operator + object so that the compiler would recognize the 'list' array. I tried using the
    Mergesort.mergesort(object.list);notation in hopes that it would work like this:
    Class.staticMethod(parameters);but either I am mistaken, misunderstood the documentation or both. Mergesort is not a variable. Any help would be appreciated, I have been hitting a brick wall for hours with Java documentation. Thanks all.

    [Javapedia: Classpath|http://wiki.java.net/bin/view/Javapedia/ClassPath]
    [How Classes are Found|http://java.sun.com/j2se/1.5.0/docs/tooldocs/findingclasses.html]
    [Setting the class path (Windows)|http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/classpath.html]
    [Setting the class path (Solaris/Linux)|http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/classpath.html]
    [Understanding the Java ClassLoader|http://www-106.ibm.com/developerworks/edu/j-dw-javaclass-i.html]
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

  • Calling a java static method from javascript

    I am running into issue while calling a java static method with a parameter from javascript. I am getting the following error. Any help is greatly appreciated.
    Thx
    An error occurred at line: 103 in the jsp file: /jnlpLaunch.jsp
    pfProjectId cannot be resolved to a variable
    =================================================
    // Java static method with one parameter
    <%!
    public static void CreateJnlpFile(String pfProjectId)
    %>
    //Script that calls java static method
    <script language="javascript" type="text/javascript">
    var pfProjectId = "proj1057";
    // Here I am calling java method
    <%CreateJnlpFile(pfProjectId);%>
    </script>
    ===================================================
    Edited by: 878645 on Mar 6, 2012 11:30 PM

    Thanks, Got what you are telling. Right now I have one jsp file which is setting the parameter 'pfProjectId' and in another .jsp I am retrieving it. But I am getting null valuue
    for the variable. I am wondering why I am getting null value in the second jsp page?.
    Thx
    ====================================================================
    <script language="javascript" type="text/javascript">
    // Setting parameter pfProjectId
    var pfProjectId = "proj1057";
    request.setParameter("pfProjectId", "pfProjectId");
    </script>
    // Using Button post to call a .jsp that creates jnlp file
    <form method=post action="CreateJnlpFile.jsp">
    <input type="submit" value="Create JNLP File">
    </form>
    //Contents of second .jsp file CreateJNLPFile.jsp
    String pfProjectId = request.getParameter("pfProjectId ");
    System.out.println( "In CreateJnlpFile.jsp pfProjectId " + pfProjectId );
    =======================================================

  • Using static methods to instantiate an object

    Hi,
    I have a class A which has a static method which instantiates it. If I were to instantiate the class A twice with it's static method within class B then you would think class B would have two instances of class A, right?
    Example:
    class A
       static int i = 0;
       public A(int _i)
           i = _i;
       public static A newA(int _i)
            return new A(_i);
    class B
        public B()
            A.newA(5);
            A.newA(3);
            System.out.println(A.i);
        public static void main(String[] args)
            B b = new B();
    }Is there really two instances of class A or just one? I think it would be the same one because if you check the int i it would be 3 and not 5. Maybe static instantiated objects have the same reference within the JVM as long as you don't reference them yourself?
    -Bruce

    It
    seems like you are the only one having trouble
    understanding the question.Well I was only trying to help. If you don't want any help, its up to you, but if that's the case then I fail to see why you bothered posting in the first place...?
    Allow me to point out the confusing points in your posts:
    you would think class B would have two
    instances of class A, right?The above makes no sense. What do you mean by one class "having" instances of another class? Perhaps you mean that class B holds two static references to instances of Class A, but in your code that is not the case. Can you explain what you mean by this?
    Is there really two instances of class
    A or just one?You have created two instances.
    >I think it would be the same one because if you
    check the int i it would be 3 and not 5.
    I fail to see what that has to do with the number of instances that have been created...?
    Maybe static instantiated objects have the
    same reference within the JVM as long as you
    don't reference them yourself????? What is a "static instantiated object"? If you mean that it was created via some call to a static method, then how is it different to creating an object inside the main method, or any other method that was called by main? (i.e. any method)
    What do you mean by "the same reference within the JVM"? The same as what?
    What happened to the first call "A.newA(5)"?
    I think it was overidden by the second call
    "A.newA(3)".As i already asked, what do you mean by this?
    If you change the line for the constructor
    in A to i = i * i you will get "9" as the
    output, if you delete the call "A.newA(3)"
    you will get "25" as the output. Yes. What part of this is cauing a problem?

  • Redefine Static Methods in ABAP OO

    Hello,
    I want to redefine an public static method and returns always an error.
    Okay, I already solved the problem with an workaround, but I still don't understand, why it is not possible to redefine static methods in ABAP OO.
    If someone can give me an plausible reason, so I don't have do die stupid. G
    Thanks for help!
    Matthias

    It is built into the language that way.  HEre is a link that may or may not give you an answer.
    redefine static method?
    Regards,
    Rich Heilman

Maybe you are looking for

  • Safari does not display text on some sites.

    I am running OSX 10.10.2 and Safari 8.03 Some sites I visit do not display text at all. For example: This site (http://neflin.org/) looks fine in Chrome, Firefox, whatever. But in Safari, it has no text at all. See below. Mail is having difficult wit

  • Need replacement FM for the Obsolete FMs provided

    Hi,         Can someone tell me what are all the FM which can be used as replacement for the following FM's. ADDRESS_MAINTAIN              ADDRESS_UPDATE_OLD            DD_PR_REDEFINE GRAPH_DIALOG    HELPSCREEN_NA_CREATE  STRING_SPLIT Thanks in advan

  • What's the best way to contact adobe for Connect help?

    We have a cloud account and 50 hosts and would like a simple way for all  to access support  city.adobeconnect.com - we cant work out what  help are we paying for and how do we get to it? Is there one number we can ring or one email to use? We find i

  • Captivate 7 Memory Game Failure

    I am using Captivate 7.  Everything in my presentation is working fine except for the Memory Game interaction.  I've created the slide for the Memory Game and it works perfectly when I preview it in Captivate.  However, when I publish, that particula

  • Why has my iPod Touch 4 Quit sync with Outlook Calendar?

    My iPod Touch 4 is merely 93 days old. Suddenly on the day my 90 day support expired, I noticed that it was no longer syncing my Calenar with Outlook on my PC yet the Contacts seem to sync Ok. Any ideas what might be causing this development? Nothing