Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Methods as parameters
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Aziz




PostPosted: Sat Jul 22, 2006 2:43 pm   Post subject: Methods as parameters

Is it possible to specify a method as a parameter in java? For example:

Java:
public void repeatMethod(int times, void method())
{
   for (i times)
   {
      method();
   }
}


As far as I know, no, but I was seeing if anyone else has add experience with this.
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Sat Jul 22, 2006 3:09 pm   Post subject: (No subject)

Not in Java. In many other languages this is possible, but not in Java.

However, you can pass an anonymous inner class. My intro Java tutorial talks about these.

Consider a very simple:

code:
interface TestInt {
   public boolean test(int a);
}

public class Example {
   public static void main(String[] args) {
      boolean passes = passesTest(42, new TestInt() {
         public boolean test(int a) {
            return a % 3 == 0;
         }
      });

      if (passes) {
         System.out.println("It's good!");
      }
   }

   public static boolean passesTest(int a, Test t) {
      return t.test(a);
   }
}


Or, again in Scala, just for fun.

code:
trait TestInt {
   def test(a: Int) : Boolean
}

object Example extends Application {
   val passes = passesTest(42, new TestInt {
      def test(a: Int) = a % 3 == 0
   })

   if (passes) {
      Console println "It's good!"
   }

   def passesTest(a: Int, t: TestInt) = t test a
}
Aziz




PostPosted: Mon Jul 24, 2006 4:19 pm   Post subject: (No subject)

Been looking around, and I found the java.lang.reflect package, it's description:

Java API Docs wrote:
Provides classes and interfaces for obtaining reflective information about classes and objects. Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.

AccessibleObject allows supression of access checks if the necessary ReflectPermission is available.

Arrays provides static methods to dynamically create and access arrays.

Classes in this package, along with java.lang.Class accommodate applications such as debuggers, interpreters, object inspectors, class browsers, and services such as Object Serialization and JavaBeans that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class.


And more specificially, the Method class. Description:

Java API Docs wrote:
public final class Method
extends AccessibleObject
implements GenericDeclaration, Member

A Method provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method).

A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.


Not sure what you could do with it yet, I haven't found much functionality, but I haven't looked to much at the rest of the package. It says often to refer to the Java Language Specification, particularly this section. Check it out anyone who's interested, might be useful? I think wtd or rizzix could find its appropriate use.
Aziz




PostPosted: Tue Jul 25, 2006 9:42 am   Post subject: (No subject)

I was fooling around a little bit, and came up with this. What do you think, wtd?

Java:
public interface MethodParameter {
    public void invoke(Object... params);
}


Java:
public class PassAMethod {
    public PassAMethod() {
        PrintNames method = new PrintNames();
        repeatMethod(5, method, "Hello", "crazy", "world!");
    }
   
    public static void main(String[] args) {
        new PassAMethod();
    }
   
    /* This method requires a method as a parameter */
    private void repeatMethod(int times, MethodParameter mp, Object... params) {
        for (int i = 0; i < times; i++) {
            mp.invoke(params);
        }
    }
   
    /* Methods used as parameters */
    private class PrintNames implements MethodParameter {
        public void invoke(Object... params) {
            String out = "";
            for (int i = 0; i < params.length; i++) {
                out += params[i].toString() + " ";
            }
            System.out.println(out);
        }
    }
}


It works, and could be implemented into program fairly easily. I've tried doing with functions, but just not working the way I like it. Here's what I've got so far:

Java:
public interface FunctionParameter<E> {
    public Class<E> invoke(Object... params);
}


Java:
public class PassAFunction {
    public PassAFunction() {
        GetNames<String> function = new GetNames<String>();
        String output =
            repeatFunction(5, function, "Hello", "crazy", "world!");
        System.out.println(output);
    }
   
    public static void main(String[] args) {
        new PassAFunction();
    }
   
    /* This method requires a function as a parameter */
    private String repeatFunction(int times, FunctionParameter fp,
            Object... params) {
        for (int i = 0; i < times; i++) {
            fp.invoke(params);
        }
    }
   
    /* Methods used as parameters */
    private class GetNames<E> implements FunctionParameter<E> {
        public Class<E> invoke(Object... params) {
            String out = "";
            for (int i = 0; i < params.length; i++) {
                out += params[i].toString() + " ";
            }
            return out;
        }
    }
}


Not to mention the number or compile errors, I believe I'm absolutely going about this the wrong way.
rizzix




PostPosted: Wed Jul 26, 2006 10:45 am   Post subject: (No subject)

Yes reflection is the way we go about doing such stuff in Java..

Let's take your pseudo-method for instance...
Java:
public void repeatMethod(int times, void method()) {
   for (i times) {
      method();
   }
}


We would rewrite it as follows to make use of reflection:
Java:

import java.lang.reflect.*;
.
.
public void repeatMethod(int times, Method method) {
   for (int i = 0; i < times; i++) {
      method.invoke(i);
   }
}


Let's say we have a class as such:
Java:
class TestClass {
    public static void printInfo(Integer i) {
        System.out.println(i);
    }
}



Then, we may invoke it like this:
Java:
repeatMethod(10, TestClass.class.getDeclaredMethod("printInfo", Integer.class));


The getDeclaredMethod of the class object takes the name of the method and the method signature (an array of classes) as variable arguments. It then retuns the respective method.

While getDeclaredMethod returns static methods of a class, getMethod will return instance methods of the class.

Both getMethod and getDeclaredMethod throw an Exception if a matching method was not found. So you have to enclose that code withing a try-block.
rizzix




PostPosted: Wed Jul 26, 2006 10:53 am   Post subject: (No subject)

As far as possible DO NOT use reflection. Simply because it is not type safe.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 6 Posts ]
Jump to:   


Style:  
Search: