Accesing database from static method on java collaboration

Hi *,
I want cache data from a oracle database in a java collaboratioon when java collaboration is enabled by emanager.
My java collaboration has a oracleOTD
I did an static method on java collaboration, but I can't access database from static method.
Thanks
Hector

hi hector,
this wont work!
regards chris

Similar Messages

  • Are static methods in Java thread safe?

    Are static methods in Java thread safe?
    thanks,
    suresh

    if static method use the instance variable
    You mean member variable, where member variables are either class variables (static) or instance variables (non-static).
    then you have to make it thread safe using
    synchronization Not necessarily. Depends on requirements and usage context.
    else in case of local var. it
    is thread safe. Not necessarily. That local variable could refer to an object that's visible to multiple threads.
    Statements like "Local variables are threadsafe but member variables aren't" are an oversimplification.
    Something is threadsafe if it cannot be made to behave incorrectly simply by running it in a multithreaded context. Determining that can be very difficult.

  • Problem with calling dispose() from static method

    I have one class, where I have this:
    EditorWindow.disposeWindow();and class EditorWindow, where I have static method
    protected static void disposeWindow() {
        dispose();
    }But, dispose() cant be called from static method. Is there any way to hide or close the EditorWindow window?

    kaneeec wrote:
    I dont have references of these windows, because it would be too difficult. They are created just by new Window().setVisible(true);It's not difficult:
    Window w = new Window();
    w.setVisible(true);Now you have a reference (w) to your window that you can later call dispose() on.
    w.dispose();dispose() isn't a static method, so you have no choice but to call it on a specific instance.

  • Can't get ClassLoader from static method.

    I'm trying to get the ClassLoader within a static method getInstance().
    public class PropertyManager {
    public static PropertyManager getInstance(String fileName) {
    //The following line returns null
    ClassLoader cl = (new Object()).getClass().getClassLoader();
    URL url = cl.getResource(fileName);
    etc...
    However if getInstance gets called from e.g. a statless session bean, a null
    is returned instead of a valid ClassLoader.
    The same code executed from a standalone java program (e.g. from
    main(String[] args)) returns a valid ClassLoader
    Why does getClassLoader behave differently in WebLogic than in a standalone
    java program?
    Thanks for you help.
    Bernie

    Sorry for the confusion. I wrote a couple of more test programs and was able
    to confirm that WL behaves exacltly the same as java does. For some reason
    my intial tests were messed up...
    getClassLoader() executed from a static method always returns null (in WL as
    well as in a java standalone program).
    In this case ClassLoader.getSystemClassLoader() will return a valid class
    loader.
    Thanks for your help.
    Bernie
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]..
    Bernhard Lenz wrote:
    I tried that as well, but getClassLoader() still returns null when
    executed
    in WL.
    I'm still not clear how getClassLoader() gets affected by running withinWL.
    >>
    >
    Very odd. Where is this class located? in the server's classpath, in ajar or
    war file? Does getClass().getClassLoader work from a non-static method inthis
    class?
    -- Rob
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]..
    You want PropertyManager.class.getClassLoader()
    -- Rob
    Bernhard Lenz wrote:
    I'm trying to get the ClassLoader within a static method
    getInstance().
    >>>>
    public class PropertyManager {
    public static PropertyManager getInstance(String fileName) {
    //The following line returns null
    ClassLoader cl = (new Object()).getClass().getClassLoader();
    URL url = cl.getResource(fileName);
    etc...
    However if getInstance gets called from e.g. a statless sessionbean, a
    null
    is returned instead of a valid ClassLoader.
    The same code executed from a standalone java program (e.g. from
    main(String[] args)) returns a valid ClassLoader
    Why does getClassLoader behave differently in WebLogic than in astandalone
    java program?
    Thanks for you help.
    Bernie

  • How to use Action listener from Static method

    Hello,
    I am begginer in Java. I am trying to add JButton and add ActionListener to it in the Java tutorial example (TopLevelDemo).
    The problem i am facing are:
    1. Since "private static void createAndShowGUI" method is static I cannot reference (this) in the method addActionLisetener when trying to add the JButton
    JButton pr = new JButton("Print Report");
         pr.addActionListener(this);
    2. If I make "private static void createAndShowGUI" a non static method then it does not run from main method giving me the error(cannot reference non-static).
    3. Where do I put actionPerformed method?
    I did not post the errors for all situations. Just asking how I can Add JButton and add ActionListener to it in the following code
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    /* TopLevelDemo.java requires no other files. */
    public class TopLevelDemo {
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("TopLevelDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create the menu bar. Make it have a cyan background.
    JMenuBar cyanMenuBar = new JMenuBar();
    cyanMenuBar.setOpaque(true);
    cyanMenuBar.setBackground(Color.cyan);
    cyanMenuBar.setPreferredSize(new Dimension(200, 20));
    //Create a yellow label to put in the content pane.
    JLabel yellowLabel = new JLabel();
    yellowLabel.setOpaque(true);
    yellowLabel.setBackground(Color.yellow);
    yellowLabel.setPreferredSize(new Dimension(200, 180));
    //Set the menu bar and add the label to the content pane.
    frame.setJMenuBar(cyanMenuBar);
    frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    Here is one way of doing it...
    JButton btn = new JButton("Click on Me");
    btn.addActionListener(new ActionListener(){
                              public void actionPerformed(ActionEvent ae){
                                // do something
                                }});here we create an anonymous inner class ActionListener and add it to our button...
    - MaxxDmg...
    - ' I am not me... '

  • Referring a member from static method

    Hello,
    Suppose I have a class:
    public class OuterClass{
    public class SomeException{}
    public static void someMethod(){
    throw new SomeException(); // how to handle this ??
    How to handle the creating of an object of the Inner Exception class from within the static method?? Is there any syntax allowing me to do that? Or, I have to declare the SomeException inner class a static class?
    Thanks.

    Or, I have to declare the SomeException inner class a static class?If your design allows for that, then you should do that anyways - and your problem will be solved - else you need to create an instance of OuterClass on which to create an instance of SomeException

  • Call Enterprise Bean (or Database) from private Method in Session-Bean

    Hi Everybody,
    I've a question regarding the possibility to call an dependency injected EJB in an private method of a session bean.
    Imagine the following.
    @Stateless
    public class SomeBean implements SomeLocal{
       @EJB
       private AnotherLocal anotherBean;
       /** Will be called from a web-app via delegate layer */
       @TransactionAttribute(TransactionAttribute.RequiresNew)
       public void someBusisnessMethod(){
           String something = this.getSomeThing();
           //Do more
       private String getSomeThing(){
          return anotherBean.aMethodWhichCallsTheEntityManager();
    }I've to refactor code with uses such Call-Hierachy and I want to know whether this is a correct way? Somebody told me that such stuff should not be made, and I quess he told me an explanation, why not to do such stuff, but unfortunally I've forgotten that. Do someone have a suggestion why not to do this? Could it blow the application to hell? Is there any difference to the following code (The way I would have done it)?
    @Stateless
    public class SomeBean implements SomeLocal{
       @EJB
       private AnotherLocal anotherBean;
        @Resource
        private SessionContext sessionContext;
       /** Will be called from a web-app via delegate layer */
       @TransactionAttribute(TransactionAttribute.RequiresNew)
       public void someBusisnessMethod(){
           SomeLocal self = this.sessionContext.getBusinessObject(SomeLocal.class);
           String something = self.getSomeThingBusinessMethod();
           //Do more
       @TransactionAttribute(TransactionAttribute.Required)
       public String getSomeThingBusinessMethod(){
          return anotherBean.aMethodWhichCallsTheEntityManager();
    }

    Found the answer by myself....
    Here it is if someone might have the same question:
    http://stackoverflow.com/questions/3381002 or if the link may down sometime the content of the answer...
    >
    The motivation here is that most EJB implementations work on proxies. You wouldn't be too far off in thinking of it as old-school AOP. The business interface is implemented by the EJB container, quite often via a simple java.lang.reflect.Proxy, and this object is handed to everyone in the system who asks for the ejb via @EJB or JNDI lookup.
    The proxy is hooked up to the container and all calls on it go directly to the container who will preform security checks, start/stop/suspend transactions, invoke interceptors, etc. etc. and then finally delegate the call to the bean instance -- and of course do any clean up required due to any exceptions thrown -- then finally hand the return value over through the proxy to the caller.
    Calling this.foo() directly, or passing 'this' to a caller so they can make direct calls as well, will skip all of that and the container will be effectively cut out of the picture. The 'getBusinessObject(Class)' method allows the bean instance to essentially get a proxy to itself so it can invoke its own methods and make use of the container management services associated with it -- interceptors, transaction management, security enforcement, etc.
    written by David Blevins

  • Anyway of accesing object from loadView() method?

    Hi Everybody,
    I am doing one application in which i am using different method for tableView.
    In have two UIViewController class
    1. firstViewController
    in loadView() metohd i have created one myView , common view , for all others sub views.
    2. secondViewController
    another sub vies i have to access myview from loadView of firstViewController but i can't understand what to do?
    Please tell me any body it would appreciated
    Thank you.

    I found a way of opening attachments to a specific bookmark. It ain't pretty but it works. If anybody needs the script, let me know.
    Kyle

  • Non-static method getRealPath cannot be referenced from a static context

    Hi, I'm fairly new to java and servlets, I get the following error referencing the line denoted in the code snippet with a ">>" I don't understand why I am getting this error message?
    Message: non-static method getRealPath(java.lang.String) cannot be referenced from a static context
    public class events extends HttpServlet implements SingleThreadModel {
      private static final String CONTENT_TYPE = "text/html";
      //Initialize global variables
      public Document xmlDocument;
      public HttpSession theSession;
      public RequestDispatcher pageInit;
      public RequestDispatcher pageHeader;
      public RequestDispatcher pageFooter;
      public String path;
      public void setPath(){
    path = getServletContext.getRealPath( "/" );  }
      public void init() throws ServletException {
      }

    Ok More Code, I am weary of posting too much? I don't know why come to think of it?
    package altitude;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import org.jdom.*;
    import altitude.sysVar;
    public class events extends HttpServlet implements SingleThreadModel {
      private static final String CONTENT_TYPE = "text/html";
      //Initialize global variables
      public Document xmlDocument;
      public HttpSession theSession;
      public RequestDispatcher pageInit;
      public RequestDispatcher pageHeader;
      public RequestDispatcher pageFooter;
      public String path;
      public void getRealPath(){
        path = ServletContext.getRealPath( "/" );
      public void init() throws ServletException {
      //Process the HTTP Get request
      public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise some Global Variables
        theSession = request.getSession( true );
        doPage( request, response );
      //Process the HTTP Post request
      public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise some Global Variables
        theSession = request.getSession( true );
        doPage( request, response );
    public void doPage( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise the variables and get the parameters from the query string.
        String eventID = request.getParameter( "eventID" );
        String dateFrom = request.getParameter( "dateFrom" );
        String dateTo = request.getParameter( "dateTo" );
        theSession.setAttribute( "Page Title", sysVar.servletTitle_events);
        Calendar theCalendar = Calendar.getInstance();
        RequestDispatcher pageInit = request.getRequestDispatcher( sysVar.servlet_initSession );
        pageInit.include( request, response );
        RequestDispatcher pageHeader = request.getRequestDispatcher( theSession.getAttribute( "Skin Directory" ) + sysVar.page_header );
        RequestDispatcher pageBody = request.getRequestDispatcher( sysVar.servletJsp_events );
        RequestDispatcher pageFooter = request.getRequestDispatcher( theSession.getAttribute( "Skin Directory" ) + sysVar.page_footer );
        //Initailize the site for this visitor this sets up the skin, and any customisations that may exist.
        //load variables, objects in to the session
        theSession.setAttribute( "Xml Document Object",  path + sysVar.data_events );
        pageHeader.include( request, response );
        pageBody.include( request, response );
        pageFooter.include( request, response );
        //remove the variables and the objects from the session
        theSession.setAttribute( "Xml Document Object", "" );
      //Clean up resources
      public void destroy() {
    }

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

  • Cannot reference from static content

    Ok, so I was working on wrapping the main program and the classes together and I come up with that error...TopSort.java:40: non-static method addVertex(java.lang.String) cannot be referenced from a static context. I know why I am getting the error, I am just not sure what to do about it. When I first wrote the main, I was literally adding in the newVertexs, doing it like this...
    Graph theGraph = new Graph();
    theGraph.addVertex("A"); // 0
    theGraph.addVertex("B"); // 1
    and that all worked great. Now I am adding in the text file and have to read the data from the file so I am doing it like this
    String toke1 = toke.nextToken();
    if (toke1.equals("vertex"))
         newVertex = toke.nextToken();
         Graph.addVertex(newVertex);
    but it throws the nonstatic error. How on earth do I go about modifying the class/main in order to circumvent that error?
    Main -
    [import java.io.*;
    import java.util.*;
    public class TopSort
    public static void main (String args[])
         File sourceFile = new File(args[0]); // access the file
            if (sourceFile.exists() == false)                                          
              System.err.println("Oops: " + sourceFile + ": No such file");
              System.exit(1);
            System.out.println(args[0] + " is the name of the file you chose");
            Graph theGraph = new Graph();
            String newVertex, startEdge, endEdge;
            try //open the file, read the file into a string and then into the list
                 FileReader fr = new FileReader(sourceFile);
                 BufferedReader br = new BufferedReader(fr);
              String input;
              while ((input = br.readLine()) != null)
                 StringTokenizer toke = new StringTokenizer(input);
                 while (toke.hasMoreTokens())
                           String toke1 = toke.nextToken();
                           if (toke1.equals("vertex"))
                           newVertex = toke.nextToken();
                           Graph.addVertex(newVertex);
                           else if (toke1.equals("edge"))
                           startEdge = toke.nextToken();
                           endEdge = toke.nextToken();
                           System.out.println(startEdge + endEdge);
                   }//close inner while
              }//close outer while
              br.close();
         }//close try
         catch (IOException e)
            System.out.println("Whoops, there's a mistake somewhere.");
    }Class
    class Vertex
       public String label;        // label (e.g. 'A')
       public Vertex(String newVertex)   // constructor
          { label = newVertex; }
       }  // end class Vertex
    class Graph
       private final int MAX_VERTS = 20;
       private Vertex vertexList[]; // list of vertices
       private int adjMat[][];      // adjacency matrix
       private int nVerts;          // current number of vertices
       private String sortedArray[];
       public Graph()               // constructor
          vertexList = new Vertex[MAX_VERTS];
                                              // adjacency matrix
          adjMat = new int[MAX_VERTS][MAX_VERTS];
          nVerts = 0;
          for(int j=0; j<MAX_VERTS; j++)      // set adjacency
             for(int k=0; k<MAX_VERTS; k++)   //    matrix to 0
                adjMat[j][k] = 0;
          sortedArray = new String[MAX_VERTS];  // sorted vert labels
          }  // end constructor
       public void addVertex(String newVertex)
          vertexList[nVerts++] = new Vertex(newVertex);
       public void addEdge(int start, int end)
          adjMat[start][end] = 1;
       public void displayVertex(int v)
          System.out.print(vertexList[v].label);
       public void topo()  // toplogical sort
          int orig_nVerts = nVerts;  // remember how many verts
          while(nVerts > 0)  // while vertices remain,
             // get a vertex with no successors, or -1
             int currentVertex = noSuccessors();
             if(currentVertex == -1)       // must be a cycle
                System.out.println("ERROR: Graph has cycles");
                return;
             // insert vertex label in sorted array (start at end)
             sortedArray[nVerts-1] = vertexList[currentVertex].label;
             deleteVertex(currentVertex);  // delete vertex
             }  // end while
          // vertices all gone; display sortedArray
          System.out.print("Topologically sorted order: \n ");
          for(int j=0; j<orig_nVerts; j++)
             System.out.print( sortedArray[j]);
          System.out.println("");
          }  // end topo
       public int noSuccessors()  // returns vert with no successors
          {                       // (or -1 if no such verts)
          boolean isEdge;  // edge from row to column in adjMat
          for(int row=0; row<nVerts; row++)  // for each vertex,
             isEdge = false;                 // check edges
             for(int col=0; col<nVerts; col++)
                if( adjMat[row][col] > 0 )   // if edge to
                   {                         // another,
                   isEdge = true;
                   break;                    // this vertex
                   }                         //    has a successor
                }                            //    try another
             if( !isEdge )                   // if no edges,
                return row;                  //    has no successors
          return -1;                         // no such vertex
          }  // end noSuccessors()
       public void deleteVertex(int delVert)
          if(delVert != nVerts-1)      // if not last vertex,
             {                         // delete from vertexList
             for(int j=delVert; j<nVerts-1; j++)
                vertexList[j] = vertexList[j+1];
                                       // delete row from adjMat
             for(int row=delVert; row<nVerts-1; row++)
                moveRowUp(row, nVerts);
                                       // delete col from adjMat
             for(int col=delVert; col<nVerts-1; col++)
                moveColLeft(col, nVerts-1);
          nVerts--;                    // one less vertex
          }  // end deleteVertex
       private void moveRowUp(int row, int length)
          for(int col=0; col<length; col++)
             adjMat[row][col] = adjMat[row+1][col];
       private void moveColLeft(int col, int length)
          for(int row=0; row<length; row++)
             adjMat[row][col] = adjMat[row][col+1];
       }  // end class Graph
    ////////////////////////////////////////////////////////////////

    I don't think I quite understand what you mean by
    that, would you elucidate? Sorry, serious brain
    fry...Sure; your addVertex() method isn't declared static. This means that you cannot call it as a class method, which was what you were doing when you wrote "Graph.addVertex()". Class members (as defined by the keyword static) refer to methods and variables that pertain to the overall class as a whole, as opposed to instance members that pertain to individual (instantiated) objects of that class.
    For example, look at the java.lang.Integer class. It has static methods like parseInt() and instance methods like intValue(). The instance method (intValue()) requires that you have instantiated an Integer object from which to get the value. You can't just call Integer.intValue(), because there's no value for the overall Integer class!
    Likewise, it doesn't make sense to require you to have an actual Integer object to parse a String to an int value. An actual Integer object wouldn't have anything to do with the process. Thus the parseInt() method is static, meaning you can call Integer.parseInt() to get the value of an int from a String.
    Hope this helps!
    &#167;

  • Non static method

    I have the following:
    import java.io.*;
    import java.util.*;
    public class BranchB2
         public static void main(String[] args)
              int pathCost, source, destination, count=0;
              int userSource, userDestination;
              String tempRead;
              ArrayList edge = new ArrayList();
              System.out.print("Start: ");
              userSource = read();
              System.out.print("End: ");
              userDestination = read();
              if(userSource == -1 || userDestination == -1)
                   System.out.println("Error in entry, Program will now exit!");
                   System.exit(0);
            try
                   FileReader file = new FileReader("graph_info - TUTE 2.txt");
                   BufferedReader fileInput = new BufferedReader(file);
                   String str = "";
                   while ((str = fileInput.readLine()) != null)//Read every line until EOF
                        String []splits = str.split(" ");
                        source = Integer.parseInt(splits[0]);
                        destination = Integer.parseInt(splits[1]);
                        pathCost = Integer.parseInt(splits[2]);
                        edge.add(new Edge(pathCost, source, destination));
                       count++;
              catch (IOException e)
                   System.out.println("ERROR: Cannot Read File!");
              int size = edge.size();
              //Create the array of linked lists
              ArrayList path = new ArrayList();
              ArrayList pathArray[] = new ArrayList[20];
              for(int i = 0; i < pathArray.length; i++)
                   pathArray[i] = new ArrayList();
              int place = runFirst(pathArray, size, userSource, edge);
              //display(place, pathArray);
              int add=0;
              sort(pathArray);
              /* This is the first part of the program,   *
               * It first gets an initial set of values   *
               * to be stored in the array so the second  *
               * can run.                                             *
              int place=0;
              for(int j=0; j<size; j++)
                   Edge temp = (Edge)edge.get(j);
                   if(temp.getSource() == userSource)
                        pathArray[place].add(new Edge(temp));
                        temp.setVisited(true);
                        place++;
              DISPLAY
              int test = place;//pathArray[0].size();
              System.out.println("Test = " + test);
              for(int k=0; k<test; k++)
                   for(int
                   Edge tempDisplay = (Edge)pathArray[k].get(0);
                   System.out.println("Start: " + tempDisplay);
         public static void display(int place, ArrayList pathArray[])
              int test = place;
              System.out.println("Test = " + test);
              for(int k=0; k<test; k++)
                   Edge tempDisplay = (Edge)pathArray[k].get(0);
                   System.out.println("Start: " + tempDisplay);
         public static int runFirst(ArrayList pathArray[], int size, int userSource, ArrayList edge)
              /* This is the first part of the program,   *
               * It first gets an initial set of values   *
               * to be stored in the array so the second  *
               * can run.                                             */
              int place=0;
              for(int j=0; j<size; j++)
                   Edge temp = (Edge)edge.get(j);
                   if(temp.getSource() == userSource)
                        pathArray[place].add(new Edge(temp));
                        temp.setVisited(true);
                        place++;     
              //System.out.println(pathArray[0].get(0));
              //System.out.println(pathArray[1].get(0));
              return place;
         public void sort(ArrayList pathArray[])
              int ff = pathArray.length;
              System.out.println(ff);
              //for(int out=pathArray.length; out>1; out--)
                   //for(int in=0; in<out; in++)
                        int one=0, two=0;
                        int sizeList = pathArray[0].size();
                        for(int current=0; current<sizeList; current++)
                             Edge tempOne = (Edge)pathArray[0].get(current);
                             one = one + tempOne.getPathCost();
                        int sizeListNext = pathArray[1].size();
                        for(int current=0; current<sizeListNext; current++)
                             Edge tempDisplay = (Edge)pathArray[1].get(current);
                             two = two + tempDisplay.getPathCost();
                        /*if(one > two)
                             ArrayList temp = pathArray[0];
                             pathArray[0] = pathArray[1];
                             pathArray[1] = temp;     
                        System.out.println("one: " + one + "two: " + two);
         public static int read()
              int value = -1;
              try
                   InputStreamReader isr = new InputStreamReader(System.in);
                   BufferedReader br = new BufferedReader(isr);
                   String tempRead = br.readLine();
                   value = Integer.parseInt(tempRead);
              catch (IOException e)
                   System.out.println("ERROR: Cannot read keyboard!");
              return value;
    }i get the error:
    C:\Users\Taurus\Desktop\University\AMI - 4517\Assignment\branchb>javac BranchB2.
    java
    BranchB2.java:77: non-static method sort(java.util.ArrayList[]) cannot be refere
    nced from a static context
                    sort(pathArray);
                    ^
    1 error
    C:\Users\Taurus\Desktop\University\AMI - 4517\Assignment\branchb>Why am I getthing this as sort is not static?

    Yorkroad's tip is correct. You'll want to create an instance of the class within the main function, then call all methods using that instance. This will allow you to have all your methods non-static. (The error is because main is a static method).
    A good way to avoid that problem is to have your main function in its own seperate class in order to maintain a truly object-oriented methodology.

  • Static methods in Session Beans problem

    Can a Stateful Session Bean have a static method?
    public static String foo();
    I tried to add a static method to a Stateful Session bean but had two problems:
    When I tried to add the static modifier to the Remote interface:
    static String foo();
    I got the following error message:
    Error(12,17): modifier static not allowed here
    When I tried to compile code calling this function :
    MyClass.foo();
    I got this message:
    Error(795,42): non-static method getNewSuffix(java.lang.String) cannot be referenced from a static context
    Even though a static method was compiled in this class. I assume it can't find the static modifier in the Remote interface which wasn't allowed. Are static methods allowed in EJB's at all?

    dear friend,
    1) Interfaces may not contain static functions!
    2) EJBs doesnt support static methods !
    Maybe you should go and learn more about Java and EJB's ?

  • Static methods in multi-thread environment.

    Sorry for this silly question, but I have no clue...
    If you're using classes with static methods in a application server environment, would that imply all threads use that same 'one in the jvm' method and would there be a possibility for performance loss?
    Is calling another static method from a static method a good idea in a multi-thread environment, with respect to performance? Somehow I seem to get this java.lang.NoClassDefFoundError. Any ideas? The classes are in the same package. I only get these kind of problems calling static methods from static methods in a multi-thread environmnent. The static methods are pure utility functions and of course do not use class state.
    Thanks for your help.

    Sorry for this question, wasn't thinking straight. I have the answer, won't post question on multiple forums.

  • Non-static method error message

    why this error message? i'm new to Java.
    Non-static method compare(java.lang.object,java.lang.Object) cannot be referenced from a static context at line 54.
    Any assistance would be greatly appreciated. Thanks.
    Calling Method;
    private static void selectionSort(Object[] objectArray)
    int min, temp;
    for (int index = 0; index < objectArray.length-1; index++)
    min = index;
    int alen = objectArray.length;
    for (int scan = index+1; scan < alen; scan++)
    (Line 54) NameComparator.compare(objectArray[scan],objectArray[min]);
    Invoked Class/Method:
    import java.util.Comparator;
    public class NameComparator implements Comparator {
    private String object, object1, firstCompare, secondCompare;
    // Constructors
    public NameComparator()
    firstCompare = object;
    secondCompare = object1;
    // Compare method
    public int compare(Object object, Object object1)
    int result = firstCompare.compareTo(secondCompare);
    return result;
    }

    That message occurs when you attempt to call a regular class method from a static class method, which usually means that you've called a regular method from main(). Remember this is main:
    public static void main( String[] args ) { . . . }The static keyword means that main() is part of the class, but not part of objects created from that class. The error message is really saying:
    // You're trying to use a method that needs an object of this class type,
    // but you don't have an object of this class type.I get this message often enough. It just means that I forgot to create an object, or that I forgot to use it when I called the method.
    class SomeThing {
      public static void main( String[] args {
        doWhatever(); // wrong - requires a SomeThing object
        SomeThing st = new SomeThing(); // got a SomeThing now
        doWhatever(); // still wrong - only works for an object
        st.doWhatever(); // finally right!
      } // end main()
      SomeThing() { . . . } // constructor for SomeThings
      doWhatever() { . . . } // method that a SomeThing can perform
    } // end of class SomeThing

Maybe you are looking for