Tech or Treat! Write an article about your scariest tech disaster to win gadgets!Learn more

x
?
Solved

Giving a method name as a parameter

Posted on 2007-11-29
4
Medium Priority
?
587 Views
Last Modified: 2008-02-01
Hello,

Mainly asking the following for java, but also interested how it applies to C# too

I have a "timer" class called Reminder which does some processing and run a method on another object every x seconds. (a new thread is created each time we create an instance of the class)

From within the main object of my application I create a new Reminder object, giving to its constructor a reference to the current object:
new Reminder(this)

the Reminder object will call a method ( for example doSomething() ) on the main object, every x seconds.

Is there any way to specify what method to be called on the main object from the Reminder object when
I create the Reminder object, instead of having to specify it withing the Reminder class ?

For example, when I create the Reminder object to give the method to be called as a parameter
in the constructor. Something like:

new Reminder(this, doSomething())

this way, I will be able to use the same Reminder class in many different situations within the application,
and be able to create many Reminder objects that will call different methods when the time is up, without having to re-write the Reminder class.

and b.t.w. is there a way (a keyword or something) to get a reference to the object from where the current object was created ? (so I don't have to give the "this" as a parameter to the Reminder constructor)
 
0
Comment
Question by:Harrris
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 17

Accepted Solution

by:
contactkarthi earned 1500 total points
ID: 20377232
in this discusion

http://forum.java.sun.com/thread.jspa?threadID=270474&messageID=1422510

see the post by mperemsky5  

i have copied it for you below
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
 
public class DynCall
{
   public void method1(Integer val)
   {
      System.out.println("method1 called with " + val);
   }
   public void method2(Integer val)
   {
      System.out.println("method2 called with " + val);
   }
 
   public void test()
   {
      try
      {
         for (int x=1; x <= 2; x++)
         {
            String methodCall = "method" + x;
            System.out.println("\nexecute: " + methodCall + " with " + x);
            Method method = this.getClass().getMethod(methodCall, 
               new Class[] { Integer.class } );
            method.invoke(this, new Object[] { new Integer(x) } );
         }
      }
      catch (InvocationTargetException e)
      {
         Exception t = (Exception)e.getTargetException();
         System.out.println(t.getMessage());
      }
      catch (Exception e)
      {
         System.out.println(e.getMessage());
      }
   }
 
   public static void main(String args[])
   {
      DynCall dc = new DynCall();
      dc.test();
   }
}

Open in new window

0
 
LVL 4

Expert Comment

by:512Thz
ID: 20377442
You can use reflection and use a method name (as string) along with the pointer (the this) of the main object.

I do not think you can find out who called you (unless you want to hack into the call stack)
void CallMethod( Object theObject, String theMethod )
{
  MethodInfo info = GetMethod( theObject, theMethod );
  info.Invoke(theObject);
}
 
MethodInfo GetMethod( Type theObjectType, String theMethod )
{
  Return     theObjectType.GetMethod(theMethod, _
                  BindingFlags.FlattenHierarchy Or _
                  BindingFlags.Instance Or _
                  BindingFlags.Public Or _
                  BindingFlags.NonPublic);
}

Open in new window

0
 
LVL 12

Expert Comment

by:andrewjb
ID: 20380630
Don't use reflection unless you don't know what method you want to call at compile time. You lose any type checking that the compiler does...

Either

1) Define an interface. Implement it in your calling object. Then Reminder calls a method on that interface

or

2) Pass in a delegate

So, something like

1):

interface IReminder { void RemindMe(); }

public class Caller : IReminder
{
 public void RemindMe() { ... do stuff here }
public  void startIt()
{
 new Reminder( this );  <-- which is passing myself as 'IReminder'
}

class Reminder
{
  public  Reminder( IReminder toCall )
  {
    ... when you're ready..
    toCall.Remind();
}
}



or 2):

public delegate void RemindDel();

class Caller
{
  void start()
  {
    new Reminder(new RemindDel(RemindMe) );
  }

  void RemindMe()
  { .. do stuff here }
}

class Reminder
{
  public Reminder( RemindDel del )
  {
     .. then call with
    del();
   }
}




0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

647 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question