Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / August 2007

Tip: Looking for answers? Try searching our database.

Dynamic method?

Thread view: 
howa - 12 Aug 2007 14:29 GMT
Hello,

I have a class, which has a method say, e.g.

int getMark(int x, int y) {

return x + y;
}

However, I want the getMark() method can be changed in runtime, maybe
change to...

int getMark(int x, int y) {

return x + 10 * y;
}

anyway...i want user to be able to change the behavior of this method
(change the mark calculation), but they don't need to recompile the
program everytime,

any method is recommended?

thanks.
Patricia Shanahan - 12 Aug 2007 14:40 GMT
> Hello,
>
[quoted text clipped - 20 lines]
>
> thanks.

Define an interface with getMark as the only method:

interface Marker{
  int getMark(int x, int y);
}

Your class would have a Marker reference, and instead of calling
getMark directly would call e.g. marker.getMark(x,y).

If there is a default Marker initialize accordingly:

Marker marker = new Marker(){
  public int getMark(int x, int y){
    return x + y;
  }
};

You can use a Marker as a constructor parameter, and/or provide a
setMarker method to change it for an existing object.

Patricia
steph - 13 Aug 2007 14:59 GMT
> Hello,
>
[quoted text clipped - 20 lines]
>
> thanks.

If you not concern with performance, you can use a java scripting
language such as Beanshell (http://www.beanshell.org/), and do sth like:

int getMark(int x, int y)
{
    Context context= new Context();
    context.put("x", new Integer(x));
    context.put("y", new Integer(y));
    return (int) Beanshell.interpret(context, "some formula involving x and
y");
}
tzvika.barenholz@gmail.com - 14 Aug 2007 16:05 GMT
> Hello,
>
[quoted text clipped - 22 lines]
>
> thanks.

Your best bet is the Strategy Design Pattern (http://en.wikipedia.org/
wiki/Strategy_pattern)

T


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.