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.

Similar Messages

  • Calling non-static command from within static method

    Hello,
    I have a static method that reads bytes from serial port, and I want to set a jTextField from within this method. but I get error that says it is not possible to call non static method from a static one. How can it be solved?

    ashkan.ekhtiari wrote:
    No, MTTjTextField is the name of jTextFiled class instance.You haven't declared any such variable in the class you posted, not to mention that such a variable name violates standard code conventions.
    This is and instance of that object actually. You haven't declared any such variable in the class you posted.
    the problem is something else. No, it isn't, based on the information you have provided. If you want accurate guidance, don't post misleading information about your problem.
    It can not be set from within static method.A question commonly asked on Java forums concerns an error message similar to the following:
    non-static variable cannot be referenced from a static context
    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term instance is often substituted for non-static, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    Once you understand this concept, you can fix your own problem.
    ~

  • Pass an object from a static method

    Hi,
    I'm trying to pass a reference to an object from a static method, but I get an error when compiling.
    Say for example I have this:
    public class obj1 {
    public void myMethod (int i, Object ob, etc...) {
    ...and I want to call this method from a method that looks like this:
    public class obj2 {
    public static int anotherMethod(...) {
    obj1.myMethod(1,this,...);
    ...Can I pass a reference from obj2 to obj1 any other way?
    Thanks alot.

    how can I get a reference to obj2 then?Pay no attention to zdude's answer - it's nonsense.
    You're confused about basic Java concepts. obj2 is a class, not an object. References point to objects, not classes. There is no obj2 object in the code you show, so you cannot have a reference to an obj2 object.
    Maybe if you post some more code, we can get an idea of what you're trying to do. You might want to try the New to Java forum.

  • Calling view controller method from component controller method

    Hi,
    Is there any way to call view controller method from component controller method?
    Thanks,

    Hi Khandal.
    You should not make you component controller dependent from a view controller.
    But what you can do is to define an event in the component controller. The view
    controller can register for this event.
    In the stage where you currently want to call the view controller method just fire
    the event. In the event handler method in the view controller you can call the
    method then.
    Why do you need to call a view controller method? Can you give more details
    about the scenario?
    Cheers,
    Sascha

  • Difference between calling static method and not static method?

    Hi,
    Suppose i want to write a util method, and many class might call this method. what is better? writing the method as static method or not static method. what is the difference. what is the advantace in what case?

    writing the method as static method or not static
    method. what is the difference.The difference is the one between static and non-static. Any tutorial or the JLs will clarify the difference, no need to repeat it here.
    what is the advantace in what case?It's usually not like you have much of a choice. If you need access to an instance's attributes, you can't make it static. Otherwise, make it static.

  • How to invoke Application Module method from entity object methods

    Hi,
    We have an existing Application Module which provides some validation logic. We are using OperatingBinding or getting the Application Module instance from the bindings and then invoking the app module methods in the view controller project.
    But in our current scenario, We need to invoke the application module method from the setAttribute method in the entity object when ever an entity attribute value is changed . I believe we can call createRootApplicationModule method to create application module instance. But this may lead to performance overhead.
    Can you please suggest, if there is any alternative to invoke the application module method inside the business components.
    What is the best way to create

    We have a pricing service, which was developed as a separate application. We need to invoke the pricing service with the change in certain attributes of the entity object and update some of the attributes of the current entity object. At present we are handling these calls to the pricing service in the ui layer in the valueChangeListener.
    But we would like to move this service call into setAttribute method as we are unable to prevent the call to the service if the model validations fail. I am looking for the best possible approach for invoking the service calls from the entity objects.
    Thanks and Regards,
    S R Prasad

  • Accessing a method from within another method

    I am having trouble accessing a method from inside a method in the same class.
    here is my code:
    public String getAns(int ans){
    answer = ans;
    ranswer = number1 * number2;
    if(answer != ranswer){
    return "No. Please try again";
    }else{
    return "Very good!";
    genQues();
    when i run this i get an Unreachable code error pertaining to genQues();
    is this allowed in Java and is there a more practical way to go about this?
    Thank you in advance

    next time use the correct code tags to post your code.
    Think of your problem like this though.
    You write
    if( something )
    then return some value;
    else
    then return some other value.
    The returns end the method here, returning the value.
    So, if the method ended at one of these 2 statements, how do you think it'll reach genQues(); ?
    Hope this helps.

  • How to call a EJB method from Session bean method

    Hi all,
    I'm new to J2EE programming. I have a simple doubt .
    I have already created a lookup method for EJB bean in Session bean .
    My question is how to call a method of an ENTITY bean (say insertRow) from SESSION bean method(Say invoke_insertRow) .
    Please provide me an example code .
    Thanks in advance.

    InitialContext ctx = new InitialContext();
         GeneralEditor editor = (GeneralEditor) ctx
                        .lookup("GeneralEditorBean/remote");
              GeneralService service = (GeneralService) ctx
                        .lookup("GeneralServiceBean/remote");
              LanMu lm = new LanMu();
              lm.setName("shdfkhsad");
              editor.add(lm);

  • Calling stored procedure from session bean method

    I have a situation like this :
    I have one method on a stateless session bean (and I mark this method as container managed transaction). For database related stuff, I am not using entity beans, I am using my own layer of OR mapping. This method does a lot of stuff and it involves many trips to the database, as a result of which the performance is very poor. I have identified certain pieces of functionality from this method which I think can be moved to stored procedures, while some of the functionality can still remain in the session bean method. So my scenario is like this :
    session bean method start
    store some data in tables(using my OR layer)
    call the stored procedure
    session bean method end
    My question is :
    Will the data that I am storing in tables from within the session bean method, be available to the code executing inside stored proc.
    secondly, how do I sync the transcation which is being initiated by the container with the transaction under which the stored proc is executing or is it that the stored procedure code will also be executing under the container managed transcation.
    Thanks
    Vimal

    Hi Vimal,
    Will the data that I am storing in tables from within
    the session bean method, be available to the code
    executing inside stored proc.There's only one way to find out (isn't there?)
    secondly, how do I sync the transcation which is
    being initiated by the container with the transaction
    under which the stored proc is executing or is it
    that the stored procedure code will also be executing
    under the container managed transcation.Again, why not just "suck it and see!"
    [Or is there some reason why you can't?]
    As I interpret the EJB specification, if the transaction attribute for your session bean method is such that it starts a transaction, then that transaction will be terminated when the method completes -- and every operation that occurs within the framework of that method will be in the one transaction.
    In other words, your database stored procedure should execute within the same transaction as your O/R mapping layer.
    However, how OC4J behaves may not exactly follow what is written in the (EJB) specification. Hence I repeat, "try it and see for yourself".
    Put it this way: as far as I know, the only way that your stored procedure would NOT see the changes made by your O/R mapping layer is if they both executed in separate transactions and the O/R mapping layer did not commit its changes before the stored procedure began its execution.
    Hope this has helped.
    Good Luck,
    Avi.

  • Workflows : Unable to call a report from a Default Method of Business Objec

    Hi,
    Good afternoon.
    Well, we had a requirement where a Business Object's Default method should call a report which in turn calls a User Defined Screen(Call Screen 100 say...) which had a Text Control with one OK button.
    In this requirement, I had created a method with all the above functionality and then tested the BUSINESS OBJECT accordingly. Well, when Testing the BO directly, I am able to get my REQUIREMENT satisfied like the METHOD is working PERFECT as per the requirement.
    Now I made it as an DEFAULT METHOD and used the same BO for a workflow. And that Workflow gets triggered with an Event within that BO. So the instance of this BO is coming to the Workflow.
    Now, I created a new Decision step and copied the standard step's task into a new Standard task. And I included this task for my new DECISION STEP. In this standard task , I had created a CONTAINER Varaible for my BO.And in my WORKFLOW, I had passed the instance of my BO in the BINDING PART of this Decision Step.
    Now, my objects and Attachments part had an HYPERLINK, but it is not executing the needed method. Why is it so?
    Do we had any limitation for this?
    Shouldn't we call any report which calls a user defined screen from a method ?
    Is there any way for solving the above problem?
    Like I want to display a TEXT CONTROL which takes COMMENTS from the Approver during the WORK ITEM PREVIEW before APPROVAL / REJECTION and this INPUT must also be shown in WORK ITEM PREVIEW in the next level.
    Someone please help me.
    Regards,
    Raja Sekhar

    Hi Raja,
    Well it is not yet afternoon for me. In fact the work day just about started
    Have you tried debugging it? Put a break point in your default method and click on the object link from the inbox and see if your method is getting executed and if it is you may find what the problem is.
    Also, have you tried with a different default method like a display method and checked if it works?
    Thanks,
    Ramki Maley.

  • Access to Class information from a static method

    There does not appear to be anyway to access the Class object from instead a static method.
    e.g. How could I convert the following code so that it works ?
    class test {
    static void printClassName() {
    System.out.println( getClass().getName() );

    The idea was to have a static method that could be
    used to make a lookup based on the classname. Being
    able to access the class name would mean that I would
    not have to reimplement for every subclass !!!!!Hmm.. what are you trying to look up? Some kind of class-specific constant information maybe?
    In general your best bet is to define an abstract method in your parent class for return of the constant value, then define a specific method in each sub-class that overrides it, retrurning the appropriate value.
    Then you're common processing just gets the value with that method.
    Using some kind of lookup on the basis of class name is much clumsier, and more inclined to run time errors. Better to use the built in virtual methods table.
    Another approach is to have the value as a parameter of the constructor of the parent class and use "super(value)" in the child classes to store
    it.

  • ADF: Can i call javascript function from java clsss method in ADF?

    Hi,
    I want to call javascript function in Java class method, is it possible in ADF? , if yes then how?
    or I need to use Java 6 feature directely?
    Regards,
    Deepak

    private void writeJavaScriptToClient(String script)
    FacesContext fctx = FacesContext.getCurrentInstance();
    ExtendedRenderKitService erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
    erks.addScript(fctx, script);
    }usage
    StringBuilder script = new StringBuilder();
    script.append( "var popup = AdfPage.PAGE.findComponentByAbsoluteId('p1');");
    script.append("if(popup != null){"); script.append("popup.show();"); script.append("}");
    writeJavaScriptToClient(script.toString());Timo

  • Static method or not static method

    I have a simple class, ClassA, with no shared class variables, and has only one static method only:
    class ClassA {
    public static void doIO (args) {
    try {
    //very time consuming I/O task
    catach (Exceptions e) { 
    //try to resolve the problem
    This doIO method will be called simultaneously from different objects.
    My questions are:
    1) Would this static method approach cause any robustness, efficiency problem? Or, should I change the method into a non-static method, and create a new instance of ClassA every time?
    2) If there are 20 threads call ClassA.doIO(args) at the same time, would the method be executed in parallel or queued?
    Many thanks.
    java9394

    Using a static method makes this implementation as efficient as possible. Since the class has no instance variables, there is no benefit, to either making it non-static, or creating multiple instances. If you have 20 threads calling it, they will run concurrently. So, if you do not like this behavior, the method can be declared both static, and synchronized.

  • In JNI how to call Java methods from native language methods

    I just build the example of java tutorial on
    http://java.sun.com/docs/books/tutorial/native1.1/implementing/method.html
    but when I excute, it says:
    Callbacks.c:1:syntax error before 'void'
    Callbacks.c:2:parse error before '*'
    Callbacks.c:In function 'Java_Callbacks_nativeMethod':
    attached:
    Callbacks.c
    JNIEXPORT void JNICALL
    Java_Callbacks_nativeMethod(JNIEnv *env, jobject obj, jint depth)
    jclass cls = (*env)->GetObjectClass(env, obj);
    jmethodID mid = (*env)->GetMethodID(env, cls, "callback", "(I)V");
    if (mid == 0) {
    return;
    printf("In C, depth = %d, about to enter Java\n", depth);
    (*env)->CallVoidMethod(env, obj, mid, depth);
    printf("In C, depth = %d, back from Java\n", depth);
    Callbacks.java
    class Callbacks {
    private native void nativeMethod(int depth);
    private void callback(int depth) {
    if (depth < 5) {
    System.out.println("In Java, depth = " + depth + ", about to enter C");
    nativeMethod(depth + 1);
    System.out.println("In Java, depth = " + depth + ", back from C");
    } else
    System.out.println("In Java, depth = " + depth + ", limit exceeded");
    public static void main(String args[]) {
    Callbacks c = new Callbacks();
    c.nativeMethod(0);
    static {
    System.loadLibrary("MyImpOfCallbacks");

    Looks like you havn't included the jni header file. Add this to the top of the .c file:
    #include "jni.h"

  • WD ABAP: call dialog window from component controller method

    Hi all,
    I need to call a dialog box from a method in the component controller. It would be helpful if u could post the code too.
    Thanks,
    Sravanthi

    Hi Maksim,
    this is the code i wrote:
    DATA: api_component  TYPE REF TO if_wd_component,
          window_manager TYPE REF TO if_wd_window_manager.
    api_component = wd_this->wd_get_api( ).
    window_manager = api_component->get_window_manager( ).
    wd_this->window = window_manager->create_window(
               window_name = 'OPTIONWD'
               close_button = abap_false ).
    wd_this->window->open( ).
    When i test it, this is the error i get.
    "An Instance of the View OPTIONWD Already Exists in the Component"
    how do i correct it?
    Thanks,
    Sravanthi

Maybe you are looking for

  • Experts VS Process Flows on OWB 10g Release 2 (Paris)

    I was looking at the the new features list for OWB 10g Release 2 (Paris), and I notices the new feature called Experts. Does anyone have any insight into when an Expert would be used instead of a Process Flow? It doesn't look like Process Flows are g

  • With new Brightbox2 router and fibre broadband, PC not shutting down on request

    Yesterday connected to fibre broadband with new Brightbox2 router. Since then have been unable to Shut Down PC, although can select Sleep OK. Also cannot access System Manager via Ctrl-Alt-Del.

  • Error when purchasing apps on iPad and iPhone

    I keep getting the following error when I update my apps. http://twitter.com/adamprocter/status/179880119488352256/photo/1 Then sometimes those other apps gp greyed out - kinda stuck.

  • TM with MyBook World Edition II

    I know that TM is only designed to work with Time Capsule or the AEBS, and trying to force it to work with any other NAS is difficult. But, I think I'd rather take the chance on a My Book World Edition II and get 4x the storage for the same price. Be

  • Applying keyword to multiple images

    I'm going through many thousands of images applying keywords. The keywords are applied with Option 1, 2, etc. I am finding that if I have more thn ne image selected, hitting option 1 applies the keyword to the first image only. Is this expected bahav