Passing methods as methods arguments

Hi,
how can I pass a method to another method?
I need something like this:
public void methodA() {
System.out.println("Hallo world");
public void methodB( Method method ) {
method();
// or
method.invoke();
and in my app:
methodB( methodA );
...of course the code below didn't work :-D
Thanks.

sorry, I didn't understood very well the 'inteface
aproach'. Do you have some example code?If the name of the method to be called truly needs to be dynamic, then this won't work but if you just want different behaviors, then you could do something like this: public interface Doer {
    void doIt();
public class Doer1 implements Doer {
    void doIt() {
        // do some stuff
public class Doer2 implements Doer {
    void doIt() {
        // do some other stuff
public class DoerDriver {
    public static void main(String[] args) {
        for (int ix = 0; ix < args.length; ix++) {
            try {
                Class klass = Class.forName(args[ix]);
                Doer doer = (Doer)klass.newInstance();
                doStuff(doer);
            catch (Exception exc) {
                System.out.println("Couldn't do " + args[ix]);
                exc.printStackTrace();
     * This method only exists to follow your model of passing the "method"--i.e., they dynamic
     * bit--to another method. We could just call doer.doIt() right inside the loop in main.
    private static void doStuff(Doer doer) {
        doer.doIt();
java DoerDriver Doer1 Doer2 Doer2 Doer1
Whether this works for you depends on what you're really trying to do.

Similar Messages

  • Array as method argument

    Is there anyway to pass an Array as argument without declare an array variable before?
    Example:
    public class MyClass
    public MyClass
    myMethod( HOW CAN I PASS AN ARRAY HERE !);
    public void myMethod(String[] myArray)
    // The method body ;

    Is there anyway to pass an Array as argument without declare an array variable before?what's the point of passing the array then?
    when you passs the array..you want to send some information and get someinformation back
    by not decalring the variable before passing in the array..it's just makes no sense
    mind as well rewrite the method to taks no argument
    but here..you do it like this
    myMethod(new String[]) // not initialized array of String
    myMethod(null); // send in a null object

  • Read only method arguments

    Can I make method arguments read only?? I want to send an object to a method and make it read only. i dont want a method to change public varables of the mthod argument object.
    Can anyone help me on this??
    Thanks,
    Vaijayanti

    Not possible, but you can pass a copy of the object, so that even if it's changed the changes aren't reflected to the original object.

  • Getting method arguments as hasmap

    Hi,
    can I get a method arguments in hashtable ? for example
    public void methodA(integer arg1,string arg2, integer arg3)
    so,
    is there any method in java that return a hashtable contains all method arguments , while running methodA.
    hashTable would be like this :
    arg1 1
    arg2 'a'
    arg3 5

    Bender_R. wrote:
    If you really need it, you can do it using Spring AOP. See AOP
    Edited by: Bender_R. on Oct 29, 2009 11:47 AMWhich won't give parameter names. And is unnecessary anyway, since you could just use a dynamic proxy without having to have all the Spring dependencies present

  • [svn:fx-trunk] 7825: Updating sample Java formatter for Eclipse projects to stop reformatting method arguments .

    Revision: 7825
    Author:   [email protected]
    Date:     2009-06-13 14:17:47 -0700 (Sat, 13 Jun 2009)
    Log Message:
    Updating sample Java formatter for Eclipse projects to stop reformatting method arguments.
    QA: No
    Doc: No
    Modified Paths:
        flex/sdk/trunk/development/eclipse/java/formatter.xml

    If you're still using Buckminster 3.6, I strongly suggest switching to 3.7 - it has a number of bug fixes and improvements. This applies to both headless, and the IDE (assuming Eclipse 3.7 Indigo).
    Matthew

  • Declaring method arguments as 'final'.

    Hi all
    Is it a good practice to declare method arguments as 'final' in java. Also please let me know how the performance would be effected.
    Ex: private int xMethod(final int i){}
    Thanks in advance.

    You are likely to find performance to be comparable whether you declare your argument as final or not.
    All it means is you cannot change the reference for an object argument or the value of a primitive argument in the method for which it is an argument.
    Note that you can still change the state of an object argument declared final! Final is not the same as const, which Java does not support.

  • Pass dynamic Command line arguments

    Hi,
    I tried to pass dynamic command line argument to Web start using the method :
    "javaws URL -D foo -D bar"
    as explained in the "Unofficial JWS/JNLP FAQ" that " You can pass your own system properties to your app using -D switch ....", but I got the following error at the start;
    error occurred while launching/running the application.
    Category: Invalid Argument error
    Too many arguments supplied: {http://...URL/my.jnlp, -Did=123 }
    p.s. I already added the"<property name='' value=''/> in the <resourse>, and modified the main class to get the parameter using System. getProperty();
    Did anyone try to this method before? What's wrong of this?
    Thanks in advance for your help.

    Thanks.
    here below is the jnlp file:
    <jnlp spec="1.0+" href="$$name" codebase="$$codebase">
    <information>
    <title>GUI Application</title>
    <vendor>PS</vendor>
    <description>PS GUI WebStart Version</description>
    <icon href="logo.jpg" />
    <offline-allowed />
    </information>
    <resources>
    <j2se version="1.3" />
    <jar href="lib/gui.jar" />
    <property name="id" value="zbc" />
    <jar href="lib/classes12.zip" />
    <jar href="lib/j2ee.jar" />
    <jar href="lib/jaas.jar" />
    <jar href="lib/jce1_2_1.jar" />
    <jar href="lib/jdom.jar" />
    <jar href="lib/xerces.jar" />
    <jar href="lib/local_policy.jar" />
    <jar href="lib/log4j.jar" />
    <jar href="lib/orion.jar" />
    <jar href="lib/sunjce_provider.jar" />
    <jar href="lib/US_export_policy.jar" />
    </resources>
    <security>
    <all-permissions />
    </security>
    <application-desc main-class="GUIFrame">
    </application-desc>
    and in the main class "GUIFrame", i use System.getProperty("id") t get the parameter, if I hardcode the value of the "id" in this jnlp file and use javaws URL, everything's fine, but not the "javaws URL -Did=value" which will return the error as mentioned.
    Thanks again for your help.

  • How to invoke adobe life cycle webservice using c++ (how to pass blob structure as argument)

    We already wrote sample code (.NET C#) to access livecycle webservice(this convert the input file into pdf file) using below link from adobe
    http://livedocs.adobe.com/livecycle/8.2/programLC/programmer/help/wwhelp/wwhimpl/common/ht ml/wwhelp.htm?context=sdkHelp&file=000088.html
    We want to write c++ client to invoke adobe life cycle webservice. I have sample code to invoke the given webservice using plain c++ but I am stuck up with 'how to pass BLOB structure as argument to CreatePDF() method' and
    plus 'how to get ouput as mapItem[]' . Is the code to convert to pdf works fine with .NET and java only? Not with c++ or VB?

    In this case the LiveCycle services are exposed as web services that can be consumed by any application language that can interact with web services. While the sample published are for c# and Java there is no reason that other web service aware languages (C++, Perl, etc) wouldn't work.
    I'm not a Microsoft C++ expert, but as far as I understand all you need to do is create a web reference and then have your C++ classes interact via the generated proxy classes. The syntax will be different, but the concept is the same

  • How to pass a command line argument to a jsp file...

    Hi guys,
    I'm writing a jsp file in which I have some java codes. I want to pass some command line arguments to that jsp file. In other words, I have some files located somewhere on my C drive and I want to pass the path to these files to my jsp file. How can it be done? I have never done before.
    Any suggestion will be very hepful...
    Thanks....

    I dont know if I truly understand your problem...
    For instance, when you place the url of your jsp you can add, at the end some parameters. For example:
    http://myserver/myapp/myjsp.jsp?MyParameter=C:\Temp\JavaTutorial.html
    In your JSP, you can place this code on a scriplet to get the value:
    String path = request.getParameter("MyParameter");
    Hope it helps.

  • Pass the command line argument (argc and argv) to a LabVIEW built shared library.

    Hello,
    I have successully use this trick to build a LabVIEW application that runs on Linux without X Display.
    http://digital.ni.com/public.nsf/allkb/5D6EC36DCF43343786257449006919E6
    I'd like to know if it's possible to pass the command line arguments ( ./TEST A B C D) directly into the shared library without having to pass the arguments using a array of strings which would require to write code using DSNewHandle, DSSetHandleSize, extract the arguments and ..... (I'm not proficient in C, but if I don't have a choice I will do it and improve my C skills).
    int main(int argc, char *argv[])
            Test(argc, argv);
            return 0;
    Thanks,
    Michel
    Solved!
    Go to Solution.

    Well, you can always flatten it back into a space separated single string and pass it like that. Basically reverse what the OS does when it calls your main function with the command line parameters. And while the first element in the array is always the program name itself you can just skip that here, but then format all the rest into a single string.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Passing final referance as argument to a method

    Hi All,
    I was wondering what is the benifit of declering a referance type in a method parameter as fianl.say
    public void foo(final Point p)
         this.p = p;
    }also does this make any big differance .
    public void foo(final Point p)
         this.p = new Point(p);
    }

    Hi All,
    I was wondering what is the benifit of declering a
    referance type in a method parameter as fianl.say
    public void foo(final Point p)
         this.p = p;
    Some people do that to avoid assignement to the argument by mistake.
    E.g p = p;
    >
    also does this make any big differance .
    public void foo(final Point p)
         this.p = new Point(p);
    Not a big difference but it makes it impossible for others to manipulate your copy of the data. (If the constructor for Point is correctly implemented)
    Kaj

  • Remote method arguments (RMI)

    Configuration:
    OC4J Release 2
    JDeveloper 9i RC
    Problem:
    I get a "ClassNotFoundException" when passing objects as arguments to a remote method.
    The object being passed implements an interface. The interface extends "Serializable" and it is available on the server (where the RMI class resides).
    Appreciate any help on this.
    Thanks,
    Ranga

    Found the solution. Thanx.

  • Find out method argument values at run time

    Hi,
    I am looking to find out the argument names and values of a method at run time. (This would allow for instance to automatically log argument names and values without writing tedious code).
    The following thread did not seem to answer this problem
    http://forum.java.sun.com/thread.jspa?forumID=4&threadID=411455
    Any suggestions welcomed
    Ben

    As there is no Method-Object representing the current method call, I doubt you will get hands on the arguments passed to the method other than referencing them or building a framework "on top" (as, e.g., AspectJ). Also, Method in reflections does not hold the names of parameters, so it will be difficult to automatically print information on more than the signature.
    The following is a not very robust, little play-around code for logging. Maybe it delivers enough information for some situations:
    public class Test {
        void test(String arg0, int arg1) {
            log(new MethodGetter(){}.get(), arg0, arg1);
        public static void main(String[] args) {
            new Test().test("zero", 1);
        public static final void log(Method method, Object ... args) {
            final StringBuilder builder = new StringBuilder();
            builder.append(method.getDeclaringClass().getSimpleName()).append('.');
            builder.append(method.getName()).append('(');
            final Class<?>[] parameterTypes = method.getParameterTypes();
            for (int index = 0; index < parameterTypes.length; index++) {
                if (index > 0) {
                    builder.append(", ");
                builder.append('(').append(parameterTypes[index].getSimpleName()).append(") ");
                if (index < args.length) {
                    builder.append(args[index]);
                } else {
                    builder.append("null");
            builder.append(");");
            System.out.println(builder.toString());
        public static abstract class MethodGetter {
            public Method get() {
                return getClass().getEnclosingMethod();
    }It will print the following:
    Test.test((String) zero, (int) 1);
    Note that MethodGetter and log and main are enclosed for test purpose only.

  • Creating arrays in method argument

    this words fine
    int[] f = {1,2,3,4};but when i try make it into one line, for example for usage as arguments to a method, it does not compile
    class test {
         public static void a(int[] in) {};
         public static void main (String[] args) {
              a( (int[]) {1,2,3,4 } );
    };i know i could just declare the array before hand, but it in my case it involves calling a super constructor, which must be the first line in the function.
    help would be appreicated

    Hi,
    a(new int[] { 1,2,3,4,});
    /Kaj

  • Passing methods to methods?

    I use to program in C++ once upon a time, and one of my favorite tricks was storing procedures in pointers so I could call procedures in parent classes from a sub class.
    Parent (say a scroll bar)
    updatePosition(int)
    child (one of the buttons)
    The child could call the updatePosition() procedure because I would pass it into the child class when I made it. It allowed me to make a button that could activate anything in my code, which was useful.
    Now I'm using Java and I wanted to do something similiar. I'm trying to make a graphical scroll bar (I plan on it's dimensions to change while it's in use, so it can't be an AWT or Swing scrollbar), and I've got some buttons made. I want to do this:
    MyScrollBar {
    int position = 0;
    void updatePosition(int amount) {
    position += amount;
    MyButton upbtn = new MyButton(updatePosition);
    MyButton downbtn = new MyButton(updatePosition);
    Just assume MyButton will respond to mouse clicks (it's workings doesn't matter really). When upbtn is clicked, I want it to be able to call the method in MyScrollBar that I passed into it when it was made. Short of making a MyButton that accepts a MyScrollBar passed to it, is there a way to call the procedure in it's parent?

    I ran into a similar problem, but I used a little trick. Make another class in that same .java file that your making which holds a static variable, where your main method sets up that JScrollbar, assigns it as a variable in that class, then other parts of your code access that JScrollBar through that class.
    class MyScrollBarHolder
      public static MyScrollBar msb;
      public static void setScrollBar(MyScrollBar msbTemp)
      {msb = msbTemp;}
      public void updatePosition()
      {//your code for handling that
    }this just goes at the end of your code. Then when a button wishes to access it, you just call MyScrollBarHolder.updatePosition() or you can get the ScrollBar itself with MyScrollBarHolder.msb
    Hope this helps
    Cheers

Maybe you are looking for

  • HELP! Different colors in Single print vs Contact Sheet print

    Aperture 1.5.1, G5, 10.4.8, Apple 30" display, Kodak 1400 Dye Sub printer, Canon 350D, shooting RAW. I have a few pictures and I want to print them. They are baby pictures so picture a little baby in standard issue baby yellow tee shirt and wrapped i

  • How to get my Lumia 720's broken screen repaired?

    Hi, My Lumia 720 just fell out my hand on to the soil, and it's screen just broke today. This is really bad news from a Nokia Phone. I want my screen to be repaired at the earliest and in the cheapest way. I am looking for some serious suggestion, an

  • Material price to be defaulted in shopping carts from Contracts in ECC

    Hi Guys, We are having a scenario wherein we need to get the price in shopping cart from contracts in ECC.In our case for a material only one contract exists for a given time frame in the ECC.We are working on classic scenario in SRM 5.5 as an add on

  • Asa5512x not listening on public subnet

    Hello I have a ASA5512x that I am trying to configure.  The problem I am having is the device is not processing packets destined for IP addresses on the same subnet as the public interface.  Packet tracer shows positive results when generating the pa

  • Web URL Re-direction thru Web Dispatcher

    Has anybody done web url re-direction using Web Dispatcher. I want to redirect URLs. Please advise what configuration I need to carry out. Thanks.