How to call a static method of a class from another class?

Hello,
I have two classes in a package. The first one
package my package;
public class class1
protected static ImageIcon createIcon(String path)
The second one
package my package;
public class class2
private ImageIcon image1;
image1 = class1.createIcon("/mypath");
This does not work since class2 cannot load the appropriate image. Where do I have to define the ImageIcon variables in class one or two and do they have to be static variables?
Thanks in advance
Christos

If the two classes are in the same package, that will work, in fact. A trivial example:
package foo;
public class Foo1 {
     protected static String getString() {
          return "World";
// Note: Member of the same package
package foo;
public class Foo2 {
     public static void main(String[] argv) {
          System.out.println("Hello "+ foo.Foo1.getString());
}However, if they are in different packages that won't work - the protected keyword guarantees that only classes derived from the class with the protected method can access it: Therefore this will not work:
package foo;
public class Foo1 {
     protected static String getString() {
          return "World";
package foo.bar;
public class Foo2{
     public static void main(String[] argv) {
          System.out.println("Hello "+ foo.Foo1.getString());
}But this will:
package foo;
public class Foo1 {
     protected static String getString() {
          return "World";
package foo.bar;
public class Foo2 extends foo.Foo1 {
     public static void main(String[] argv) {
          System.out.println("Hello "+ foo.Foo1.getString());
}I think you should read up a bit more about packages and inheritance, because you're going to have a lot of trouble without a good understanding of both. Try simple examples first, like the above, and if you hit problems try to produce a simple test case to help you understand the problem rather than trying to debug your whole application.
Dave.

Similar Messages

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

  • How to call a specific method in a servlet from another servlet

    Hi peeps, this post is kinda linked to my other thread but more direct !!
    I need to call a method from another servlet and retrieve info/objects from that method and manipulate them in the originating servlet .... how can I do it ?
    Assume the originating servlet is called Control and the servlet/method I want to access is DAO/login.
    I can create an object of the DAO class, say newDAO, and access the login method by newDAO.login(username, password). Then how do I get the returned info from the DAO ??
    Can I use the RequestDispatcher to INCLUDE the call to the DAO class method "login" ???
    Cheers
    Kevin

    Thanks for the reply.
    So if I have a method in my DAO class called login() and I want to call it from my control servlet, what would the syntax be ?
    getrequestdispatcher.include(newDAO.login())
    where newDAO is an instance of the class DAO, would that be correct ?? I'd simply pass the request object as a parameter in the login method and to retrieve the results of login() the requestdispatcher.include method will return whatever I set as an attribute to the request object, do I have that right ?!!!!
    Kevin

  • How to call a static method of a class (continued)

    In reference to the above topic posted one week ago I give you the relative code. The problem is resolved and it was the following one (amazing for me since I looked for any possible error in the code like the one posted in my article but I could never imagine this trivial thing.........):
    the package name which is the directory with the appropriate class files should not extend the lenght of 8 characters!!! Initially I had a package named Applications (too long for DOS...) and when I renamed it to Test everything worked. Any suggestion on how to overcome this DOS filesystem problem?
    Christos
    Here is my simplified code
         package test;
         import java.io.*;
         import java.net.URL;
         import javax.swing.*;
         import java.beans.*;
         import java.awt.*;
         import java.awt.event.*;
         public class myapplet extends JApplet
         private MyClass myframe;
         private JDesktopPane desktop;
         private Dimension d;
    public void init() {
    myframe= new MyClass();
    desktop = new JDesktopPane();
    d=desktop.getSize();
    try {
    javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
    createGUI();
    } catch (Exception e) {
    System.err.println("createGUI didn't successfully complete");
         private void createGUI() {
         myframe.pack();
         myframe.setBounds(0,0,d.width,d.height);
         desktop.add(myframe);
         this.getContentPane().add(desktop);
         try {
         myframe.setMaximum(true);
         } catch (PropertyVetoException e) {
         e.printStackTrace();
         myframe.setVisible(true);
    protected static ImageIcon createAppletImageIcon(String path,
    String description)
    int MAX_IMAGE_SIZE = 75000; //Change this to the size of
    //your biggest image, in bytes.
    int count = 0;
    BufferedInputStream imgStream = new BufferedInputStream(
    myapplet.class.getResourceAsStream(path));
    if (imgStream != null)
    byte buf[] = new byte[MAX_IMAGE_SIZE];
    try {
    count = imgStream.read(buf);
    } catch (IOException ieo) {
    System.err.println("Couldn't read stream from file: " + path);
    try {
    imgStream.close();
    } catch (IOException ieo) {
    System.err.println("Can't close file " + path);
    if (count <= 0) {
    System.err.println("Empty file: " + path);
    return null;
    return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf),
    description);
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    followed by the class MyClass
    package test;
         import javax.swing.*;
         import java.awt.*;
         import java.awt.event.*;
         public class MyClass extends JInternalFrame
         private JLabel jl;
         private String myicon1="images/myimage.gif";
         private ImageIcon image1;
         public MyClass()
         super ( "This is my application",false,true,true,false);
         setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    image1= myapplet.createAppletImageIcon(myicon1,"");
    jl = new JLabel("This is my image",
              image1,JLabel.CENTER);
    jl.setFont (new Font("Times-Roman",Font.BOLD, 17));
    getContentPane().add(jl);
    and finally the html file with the applet tag:
    <APPLET CODE = "test.myapplet" width=760 height=380>
    </APPLET>

    I have to say that everything works fine even with
    long package names besides the loading of the image in
    MyClass (in fact you see the JInternalFrame with the
    JLabel without icon!). Since I never saw an error in
    the Sun Java Console or the DOS window I tried this
    last solution, i.e. to shorten the package name. Only
    then the icon appears in the label......strange thingsThere shouldn't be a problem with long package (and hence long directory) names.
    private String myicon1="images/myimage.gif"; // which becomes the 'path' variable below
    BufferedInputStream imgStream = new BufferedInputStream(
    myapplet.class.getResourceAsStream(path));So are you sure you are always putting this images subdirectory underneath where your myapplet class lives? If myapplet.class lives in /foo/bar/mypackage, belongs to the 'mypackage' package, and your classpath includes /foo/bar, then your gif file better be at /foo/bar/mypackage/images/myimage.gif (or actually at mypackage/images/myimage.gif from any classpath root)

  • 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 function in one .js file from another .js file

    Hello Techies,
    I am trying to call a function in two.js file from one.js file.
    Here is my code
    one.js
    <script>
    document.write("<script type='text/javascript' src='/htmls/js/two.js'> <\/script>");
         function one()
                        var a;
                       two(a);
              }two.js
                  function two(a)
                          alert("two");
                      }But the function two() is not working.
    How can I do this one??
    regards,
    Krish

    I think there is a syntax error in line
    document.write("<script type='text/javascript' src='/htmls/js/two.js'> <\/script>");
    end tag <\/script> is wrong.

  • Initializer block not called when static method called

    public class Initializer {
         Initializer(){
              System.out.println("Constructor called");
                   System.out.println("CLASS INITIALIZED");
         static void method(){
              System.out.println("Static method called");
         public static void main(String[] args) {
              Initializer.method();
    From the JLS
    A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
    T is a class and an instance of T is created.
    T is a class and a static method declared by T is invoked.
    [b]
    But when i call the static method , if the class is initialized shouldnt the initializer block be called, it is not called, why.

    Perhaps running something like this will add a little more colour?:
    public class Initializer {
        static {
            System.out.println("First static initializer");
            System.out.println("First instance initializer");
        Initializer() {
            System.out.println("Constructor");
        static {
            System.out.println("Second static initializer");
            System.out.println("Second instance initializer");
        static void staticMethod() {
            System.out.println("staticMethod");
        void instanceMethod() {
            System.out.println("instanceMethod");
        public static void main(String[] args) {
            System.out.println("main");
            staticMethod();
            new Initializer().instanceMethod();
    }

  • How to Call Event Handler Method in Another view

    Hi Experts,
                       Can anybody tell me how to call Event handler Method which is declared in View A ,it Should be Called in
      view B,Thanks in Advance.
    Thanks & Regards
    Santhosh

    hi,
    1)    You can make the method EH_ONSELECT as public and static and call this method in viewGS_CM/ADDDOC  using syntax
        impl class name of view GS_CM/DOCTREE=>EH_ONSELECT "method name.
                 or
    2)The view GS_CM/ADDDOC which contains EH_ONSELECT method has been already enhanced, so I can't execute such kind of operation one more time.
                         or
    3)If both views or viewarea containing that view are under same window , then you can get the instance ofGS_CM/DOCTREE from view GS_CM/ADDDOC  through the main window controller.
    lr_window = me->view_manager->get_window_controller( ).
        lv_viewname = 'GS_CM/DOCTREE '.
      lr_viewctrl ?=  lr_window ->get_subcontroller_by_viewname( lv_viewname ).
    Now you can access the method of view GS_CM/DOCTREE .
    Let me know in case you face any issues.
    Message was edited by: Laure Cetin
    Please do not ask for points, this is against the Rules of Engagement: http://scn.sap.com/docs/DOC-18590

  • Call a static method via RFC

    Hello people,
    How can I call a static method via RFC?
    I am in SRM and would like to call a static method defined in ECC.
    What is necessary to be configured in this class/method?
    Thanks!!!

    You may need to write RFC in ECC and call it from SRM
    and write following code in RFC for call a static method
    reference_obj=>method_name
    EXPORTING

  • How to execute a static method twice

    Hi all,
    In the attached code, as you can see I call the method at.sendRequestString(), twice from main() method.
    The first line in sendRequestString() method is Authenticator.setDefault(new MyAuthenticator());
    Authenticator is an abstract class and setDefault is a static method in that class.
    When I call sendRequestString() for the second time, Authenticator.setDefault(new MyAuthenticator()); is not executed. ie; Authenticator.setDefault gets executed once and only once.
    Does this happen because that Authenticator.setDefault is a static method and it will be executed only once?
    If yes, how can I make it work for the second time?
    Here is my simple Java code. The username and password given in the code are just sample ones.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Authenticator;
    import java.net.MalformedURLException;
    import java.net.PasswordAuthentication;
    import java.net.URL;
    public class GetAuthenticatedData
         public String address;
         static String username;
         static String password;
         public GetAuthenticatedData(String address){
              this.address = address;
         public String sendRequestString()
              Authenticator.setDefault(new MyAuthenticator());//BEING STATIC METHOD, SET DEFAULT CALLED ONLY ONCE
             String str = null;
             try {
                 URL url = new URL(address);
                 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                 while (( str = in.readLine()) != null) {
                      return str;
                 in.close();
             } catch (MalformedURLException e) {
                  System.out.println("e1"+e);
             } catch (IOException e) {
                  System.out.println("e2"+e);
             Authenticator.setDefault(null);
              return str;
         public static void main(String args[]){
              username = "username1";
              password = "password1";
              GetAuthenticatedData at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username1 and password1"+at.sendRequestString());
              username = "username2";
              password = "password2";
              at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username2 and password2 "+at.sendRequestString());
    class MyAuthenticator extends Authenticator {
         public MyAuthenticator(){
              getPasswordAuthentication();
              protected PasswordAuthentication getPasswordAuthentication() {
                   PasswordAuthentication auth = new PasswordAuthentication(GetAuthenticatedData.username, GetAuthenticatedData.password.toCharArray());
                 System.out.println("Username"+auth.getUserName());
                 System.out.println("Password"+new String(auth.getPassword()));
                   return auth;
    }Please help with an appropriate solution.
    Any help in this regard will be well appreciated with dukes.
    Anees

    Thanks for your valuable help Looce. But it still does not solve the problem.
    Here is how I used your code.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Authenticator;
    import java.net.MalformedURLException;
    import java.net.PasswordAuthentication;
    import java.net.URL;
    public class GetAuthenticatedData
         public String address;
         static String username;
         static String password;
         public GetAuthenticatedData(String address){
              this.address = address;
         MyAuthenticator authenticator = new MyAuthenticator("username1","password1".toCharArray());
         public String sendRequestString(String user, String pass)
              authenticator.setUsername(user);
              authenticator.setPassword(pass.toCharArray());
              Authenticator.setDefault(authenticator);
             String str = null;
             try {
                 URL url = new URL(address);
                 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                 while (( str = in.readLine()) != null) {
                      return str;
                 in.close();
             } catch (MalformedURLException e) {
                  System.out.println("e1"+e);
             } catch (IOException e) {
                  System.out.println("e2"+e);
             Authenticator.setDefault(null);
              return str;
         public static void main(String args[]){
              username = "username1";
              password = "password1";
              GetAuthenticatedData at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username1 and password1"+at.sendRequestString("username1","password1"));
              username = "username2";
              password = "password2";
              at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username2 and password2 "+at.sendRequestString("password2","password2"));
    * This class implements an Authenticator whose username and password information can
    * change over time.
    * @author Cynthia G., Sun Java forums: http://forums.sun.com/thread.jspa?messageID=10504183
    class MyAuthenticator extends java.net.Authenticator {
      /** Stored user name. */
      private String username;
      /** Stored password. */
      private char[] password;
      /** Constructs an instance of MyAuthenticator with the given initial user name
       * and password. These may be modified with the setUsername and setPassword
       * methods.
      public MyAuthenticator(String username, char[] password) {
        this.username = username;
        this.password = password;
      public void setUsername(String username) { this.username = username; }
      public void setPassword(char[] password) { this.password = password; }
      protected java.net.PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }
    }

  • How to call a bean method from javascript event

    Hi,
    I could not find material on how to call a bean method from javascript, any help would be appreciated.
    Ralph

    Hi,
    Basically, I would like to call a method that I have written in the page java bean, or in the session bean, or application bean, or an external bean, from the javascript events (mouseover, on click, etc...) of a ui jsf component. I.e., I would like to take an action when a user clicks in a column in a datatable.
    Cheers,
    Ralph

  • How to call a AM method with parameters from Managed Bean?

    Hi Everyone,
    I have a situation where I need to call AM method (setDefaultSubInv) from Managed bean, under Value change Listner method. Here is what I am doing, I have added AM method on to the page bindings, then in bean calling this
    Class[] paramTypes = { };
    Object[] params = { } ;
    invokeEL("#{bindings.setDefaultSubInv.execute}", paramTypes, params);
    This works and able to call this method if there are no parameters. Say I have to pass a parameter to AM method setDefaultSubInv(String a), i tried calling this from the bean but throws an error
    String aVal = "test";
    Class[] paramTypes = {String.class };
    Object[] params = {aVal } ;
    invokeEL("#{bindings.setDefaultSubInv.execute}", paramTypes, params);
    I am not sure this is the right way to call the method with parameters. Can anyone tell how to call a AM method with parameters from Manage bean
    Thanks,
    San.

    Simply do the following
    1- Make your Method in Client Interface.
    2- Add it to Page Def.
    3- Customize your Script Like the below one to Achieve your goal.
    BindingContainer bindings = getBindings();
    OperationBinding operationBinding = bindings.getOperationBinding("GetUserRoles");
    operationBinding.getParamsMap().put("username", "oracle");
    operationBinding.getParamsMap().put("role", "F1211");
    operationBinding.getParamsMap().put("Connection", "JDBC");
    Object result = operationBinding.execute();
    if (!operationBinding.getErrors().isEmpty()) {
    return null;
    return null;
    i hope it help you
    thanks

  • Can we call a static method without mentioning the class name

    public class Stuff {
         public static final int MY_CONSTANT = 5;
         public static int doStuff(int x){ return (x++)*x;}
    import xcom.Stuff.*;
    import java.lang.System.out;
    class User {
       public static void main(String[] args){
       new User().go();
       void go(){out.println(doStuff(MY_CONSTANT));}
    }Will the above code compile?
    can be call a static method without mentioning the class name?

    Yes, why do it simply?
    pksingh79 wrote:
    call a static method without mentioning the class name?For a given value of   "without mentioning the class name".
        public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
            Class<?>[] types = new Class<?>[args.length];
            for(int i=0;i<args.length;++i) types[i] = args==null?Object.class:args[i].getClass();
    return Class.forName(className).getDeclaredMethod(methodName,types).invoke(null,args);

  • How to call jpf controller method from javascript

    Can any one help me how to call pageflow controller method from JavaScript.\
    Thanks.

    Accessing a particular pageflow method from Javascript is directly not possible unless we do some real funky coding in specifying document.myForm.action = xyz...Heres what I tried and it did not work as expected: I found another workaround that I will share with you.
    1. In my jsp file when I click a button a call a JavaScript that calls the method that I want in pageflow like this: My method got invoked BUT when that method forwards the jsp, it lost the portal context. I saw my returned jsp only on the browser instead of seeing it inside the portlet on the page of a portal. I just see contents of jsp on full browser screen. I checked the url. This does make the sense. I do not see the url where I will have like test1.portal?_pageLabe=xxx&portlet details etc etc. So this bottom approach will notwork.
    document.getElementById("batchForm").action = "/portlets/com/hid/iod/Batches/holdBatch"; // here if you give like test1.portal/pagelable value like complete url...it may work...but not suggested/recommended....
    document.getElementById("batchForm").submit;
    2. I achieved my requirement using a hidden variable inside my netui:form tag in the jsp. Say for example, I have 3 buttons and all of them should call their own action methods like create, update, delete on pageflow side. But I want these to be called through javascript say for example to do some validation. (I have diff usecase though). So I created a hidden field like ACTION_NAME. I have 3 javascript functions create(), update() etc. These javascripts are called onclick() for these buttons. In thse functions first I set unique value to this hiddent field appropriately. Then submit the form. Note that all 3 buttons now go to same common action in the JPF. The code is like this.
    document.getElementById("ACTION_NAME").value = "UPDATE";
    document.getElementById("batchForm").submit.
    Inside the pageflow common method, I retriev this hidden field value and based on its value, I call one of the above 3 methods in pageflow. This works for me. There may be better solution.
    3. Another usecase that I want to share and may be help others also. Most of the time very common usecase is, when we select a item in a drop bos or netui:select, we want to invoke the pageflow action. Say we have 2 dropdown boxes with States and Cities. Anytime States select box is changed, it should go back to server and get new list of Cities for that state. (We can get both states and cities and do all string tokenizer on jsp itself. But inreality as per business needs, we do have to go to server to get dynamic values. Here is the code snippet that I use and it works for all my select boxes onChange event.
    This entire lines of code should do what we want.
    <netui:anchor action="selectArticleChanged" formSubmit="true" tagId="selectPropertyAction"/>                    
    <netui:select onChange="document.getElementById(lookupIdByTagId('selectPropertyAction',this )).onclick();" dataSource="pageFlow.selectedArticleId" >
    <c:forEach items="${requestScope.ALL_ARTICLE}" var="eachArticle">
    <%-- workshop:varType="com.hid.iod.forms.IoDProfileArticleRelForm" --%>
    <netui:selectOption value="${eachArticle.articleIdAsString}">${eachArticle.articleItemName}</netui:selectOption>
    </c:forEach>               
    </netui:select>
    See if you can build along those above lines of code. Any other simpler approches are highly welcome.
    Thanks
    Ravi Jegga

  • Calling a static method when starting the server???

    Hi,
    i wanted to call a static method of a java class,
    whenever i start the server.
    plz give some input on this.
    thanks and regards
    siva

    Siva -- Can you be more specific as to the problem you are trying to solve (why do you want to call this static method,.)
    The reason I ask is that there are some ways to make this happen but they may have limitations
    that won't work for you. For instance, you can create a servlet that calls your class' static method and then make the
    servlet be loaded on startup.
    Thanks -- Jeff

Maybe you are looking for