Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Passing a Method Name to a Method

Reply
Thread Tools

Passing a Method Name to a Method

 
 
Gene Wirchenko
Guest
Posts: n/a
 
      06-22-2011
Dear Jav'ers:

Maybe I will find this after searching more, but so far, no good.

I want to pass a parameter of a method name to another method.

N.B.: I do not want to pass the method name as a string. I want
to pass it as a pointer / reference / whatever term is used for this
in Java.

I am doing this to test different ways of parsing. I want to be
able to do this (timing details not shown):

for (i=1; i<=nRepetitions; i++)
Parse(ThisWay);

for (i=1; i<=nRepetitions; i++)
Parse(ThatWay);

static void Parse
(
????? What goes here? MethodToUse
)
{
...
????? How exactly is this done? MethodToUse(actual parms)
...
}

static returntype ThisWay(formal parms)
{...}

static returntype ThatWay(formal parms)
{...}

The signatures and return types of ThisWay() and ThatWay() would
be identical.

Sincerely,

Gene Wirchenko
 
Reply With Quote
 
 
 
 
Fuschia, President-Elect of the Bright Purplish-Green Council
Guest
Posts: n/a
 
      06-22-2011
On 22/06/2011 3:46 PM, Gene Wirchenko wrote:
> Dear Jav'ers:
>
> Maybe I will find this after searching more, but so far, no good.
>
> I want to pass a parameter of a method name to another method.
>
> N.B.: I do not want to pass the method name as a string. I want
> to pass it as a pointer / reference / whatever term is used for this
> in Java.


Unfortunately, you can't do this easily or efficiently (you'd need to
use the Reflection API's Method objects) in Java; what you really want
is a functional language like Clojure or Scala.

If you really must use Java, define an interface that ThisWay and
ThatWay can be instances of and which specify a parse method, and pass
an instance to the parser class's method. (The so-called "strategy
pattern".)
 
Reply With Quote
 
 
 
 
Stefan Ram
Guest
Posts: n/a
 
      06-22-2011
Gene Wirchenko <(E-Mail Removed)> writes:
>I want to pass a parameter of a method name to another method.


In Java, there is no such thing as »a parameter of a method name«.
There are »parameter declarations«, which are a part of a
»method declaration«. (Vulgo: »parameters« of »methods«
[not »method names«]).

> N.B.: I do not want to pass the method name as a string.


A method /name/ /is/ a string.

>I want to pass it as a pointer / reference / whatever term is
>used for this in Java.


The closest you can get is

http://download.java.net/jdk7/docs/a...ct/Method.html

, although you may not like it.

Or use a »method object«, that is an object implementing
an interface with a single method, such as, for example,

http://download.java.net/jdk7/docs/a.../Runnable.html

or

http://download.java.net/jdk7/docs/a.../Callable.html

(it is called »function object« or »functor« in the C++ world.)

Such an object represents a methods as a run-time value.

Java 8 will have lambda expressions.

 
Reply With Quote
 
markspace
Guest
Posts: n/a
 
      06-22-2011
On 6/22/2011 12:46 PM, Gene Wirchenko wrote:
> Dear Jav'ers:
>
> Maybe I will find this after searching more, but so far, no good.
>
> I want to pass a parameter of a method name to another method.



As others have said, you can't do this literally. However you have a
few options using interfaces, classes, dependency injection, and good
ol' software engineering.

First, the interface/class method:

public class Parser {
final private Language parser;
public Parser( Language parser ) {
this.parser = parser;
}
public parse( Reader in ) {
parser.parse( in );
}
}

Here, you use a Parser which uses dependency injection to determine
which language you are going to parse. You use it like this:

Parser p = new Parser( new JavaParser() );
p.parse( System.in ); // parse stdin

Where JavaParser is:

public class JavaParser implements Language { ...

and

public interface Language {
parse( Reader in );
}

You could of course pass in the language at the same time, but that's a
little less OOD.

public class Parser {
public static parse( Language parser, Reader in ) {
parser.parse( in );
}
}

Note that the "don't do it in Java" guy, Fuschia, is off his rocker.
This is very efficient in Java as the JVM will recognize the JavaParser
class is effectively final and optimize the call to use non-virtual calls.

You can also do similar things with Runnable or Callable, which just
avoids declaring a type. Since declaring a type isn't that big of a
deal, this is usually poor solution unless you are in fact spawning
threads and using the concurrency API directly.

public class Parser {
final private Runnable parser;
public Parser( Runnable parser ) {
this.parser = parser;
}
public parse() {
parser.run();
}
}

You might call this with an anonymous class rather than declaring a yet
another type, however again that might not really be worth it. I'm
drawing a blank here how to pass in arguments to the run method, so I'll
cheat:

Parser p = new Parser( new Runnable() {
private final Reader in = System.in;
public void run() {
new JavaLanguage.doIt( in );
}
} );
p.parse(); // parse stdin

Note that when you see this for "real", say in the Java API, you'll
typically use a factory method, not instantiate an injectable object.
(For example, both the ScriptEngineManager and
javax.xml.parsers.DocumentBuilder use factory methods.) So don't ignore
the Factory Pattern in your own designs as well.

Parser p = Parser.getParser( "Java" );
p.parse( System.in ); // parse stdin

No code compiled or tested.
 
Reply With Quote
 
Eric Sosman
Guest
Posts: n/a
 
      06-23-2011
On 6/22/2011 3:46 PM, Gene Wirchenko wrote:
> Dear Jav'ers:
>
> Maybe I will find this after searching more, but so far, no good.
>
> I want to pass a parameter of a method name to another method.
>
> N.B.: I do not want to pass the method name as a string. I want
> to pass it as a pointer / reference / whatever term is used for this
> in Java.


(It's "reference." The only data items a Java program can
manipulate are primitives and references.)

Pass a reference to an object that implements an agreed-upon
interface. See, for example, the two-argument version of
java.util.Arrays.sort().

Y'know, Gene, you've been asking a spate of pretty elementary
questions. Maybe some time with a textbook or other documentation
would be helpful, or possibly relocation to c.l.j.help, which is
more beginner-oriented.

--
Eric Sosman
http://www.velocityreviews.com/forums/(E-Mail Removed)d
 
Reply With Quote
 
Joshua Cranmer
Guest
Posts: n/a
 
      06-23-2011
On 06/22/2011 03:46 PM, Gene Wirchenko wrote:
> I want to pass a parameter of a method name to another method.


No you don't. You essentially want to go with the interface approach, as
the prior responders to myself have said.

Java does not have a concept of a function pointer or method handle. It
is possible to emulate this to some degree with reflection, but if you
are contemplating calling Method.invoke, you are almost always doing
something wrong.

> static returntype ThisWay(formal parms)
> {...}
>
> static returntype ThatWay(formal parms)
> {...}


Why are you having static methods (on the same class, I presume) for two
different ways of parsing instead of using separate parser classes?

--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth
 
Reply With Quote
 
Fuschia, President-Elect of the Bright Purplish-Green Council
Guest
Posts: n/a
 
      06-23-2011
On 22/06/2011 5:14 PM, markspace wrote:
> public interface Language {
> parse( Reader in );
> }
>
> You could of course pass in the language at the same time, but that's a
> little less OOD.
>
> public class Parser {
> public static parse( Language parser, Reader in ) {
> parser.parse( in );
> }
> }
>
> Note that the "don't do it in Java" guy, Fuschia, is off his rocker.


Wrong.

> This is very efficient in Java as the JVM will recognize the JavaParser
> class is effectively final and optimize the call to use non-virtual calls.


I never claimed otherwise. In fact that approach is exactly what I
recommended he use if he insisted on not going to a JVM language that
better supports functional programming.

It was using the Reflection API and Method objects that I said would not
be efficient.
 
Reply With Quote
 
Arved Sandstrom
Guest
Posts: n/a
 
      06-23-2011
On 11-06-22 11:30 PM, Joshua Cranmer wrote:
> On 06/22/2011 03:46 PM, Gene Wirchenko wrote:
>> I want to pass a parameter of a method name to another method.

>
> No you don't. You essentially want to go with the interface approach, as
> the prior responders to myself have said.
>
> Java does not have a concept of a function pointer or method handle. It
> is possible to emulate this to some degree with reflection, but if you
> are contemplating calling Method.invoke, you are almost always doing
> something wrong.
>
>> static returntype ThisWay(formal parms)
>> {...}
>>
>> static returntype ThatWay(formal parms)
>> {...}

>
> Why are you having static methods (on the same class, I presume) for two
> different ways of parsing instead of using separate parser classes?
>

At this stage of the game, considering the original problem statement, I
haven't seen any compelling arguments for not doing

for (i=1; i<=nRepetitions; i++)
ParseThisWay(args);

and

for (i=1; i<=nRepetitions; i++)
ParseThatWay(args);

(Note the editing from the original.) I mean, there's a strong
distinction between testing different methods of parsing (which the OP
mentioned he was doing) and coding your application to permit selection
of arbitrary parsing method.

We may be thinking at cross-purposes here. It could be that Gene,
incidental to the problem of testing parsing techniques, might really
just be curious as to whether it's possible to do something like he
asked about, i.e. function pointer-looking things. Practically everyone
else seems to have posited a Parsing U"ber-Problem which demands an
interface/pattern-based adaptive dynamic solution for production use,
and for my part I'm suggesting that if the actual issue is simply
adhoc/experimentally testing a couple of different chunks of code why
not just hardcode a couple of different methods (the engineering Good
Enough approach).

AHS
 
Reply With Quote
 
Gene Wirchenko
Guest
Posts: n/a
 
      06-23-2011
On Wed, 22 Jun 2011 22:09:05 -0400, Eric Sosman
<(E-Mail Removed)> wrote:

[snip]

> Y'know, Gene, you've been asking a spate of pretty elementary
>questions. Maybe some time with a textbook or other documentation
>would be helpful, or possibly relocation to c.l.j.help, which is
>more beginner-oriented.


Yes, I know. I have been reading the on-line documentation, but
it is often hard to find out how to do something. I usually already
know the concept, but if it is called something different in Java, it
can be hard to find the documentation.

What is the difference between the two newsgroups other than that
c.l.j.help seems fairly moribund?

Sincerely,

Gene Wirchenko
 
Reply With Quote
 
Arved Sandstrom
Guest
Posts: n/a
 
      06-23-2011
On 11-06-23 11:01 AM, Stefan Ram wrote:
> Arved Sandstrom <(E-Mail Removed)> writes:
>> At this stage of the game, considering the original problem statement, I
>> haven't seen any compelling arguments for not doing
>> for (i=1; i<=nRepetitions; i++)
>> ParseThisWay(args);
>> and
>> for (i=1; i<=nRepetitions; i++)
>> ParseThatWay(args);

>
> This is procedural programming, while the approach with the
> same method name in different classes is object-oriented
> programming, because it would use polymorphism.
>
> Under specific and fixed requirements, it is possible that
> both solutions are equally well. However, requirements often
> change in time.
>
> In the general case, object-oriented programing is better,
> because it allows to add another parse method by adding
> another (third) parse class /without changing/ most of the
> other code and thus fulfills the open-closed principle,
> while procedural programming usually would required code
> changes in more places when adding a third way to parse.
>

You're absolutely correct in almost all respects. I'd go further and
assert that in an adhoc, experimental situation then the procedural-type
solution (which is nothing to hold your nose for; a great deal of Java
code _is_ inevitably procedural, and later-generation hybrid- or
multi-paradigm languages acknowledge this reality) might even be better
because the hard-wiring looks adhoc and experimental and
throwaway...precisely because it _is_.

Setting things up the "OO way" in this situation, while aesthetically
appealing, also means that you've made a deliberate design decision to
allow for more straightforward swapping of parse logic. This _should_ be
a deliberate design choice. I'm sure you've read the odd article that
decries elaboration of implementation on a "what if?" and "just in case"
basis - I'm mostly in that camp.

This may seem like a trivial example - no harm done, and all that - but
over-engineering starts exactly with thought processes like this. And
the second you start designing and coding stuff to be more adaptable and
general-purpose, the more danger there is that the code is going to be
kept, and go into production. Not so desirable if the requirement didn't
exist. I know requirements often change, but my philosophy on that is,
provided that your project costing structure accurately assigns change
request costs to the people changing the requirements, make the cost of
requirements changes public, highly visible, and somewhat painful.

To return to my original point, with the added context of your reply
above, my argument remains this: we don't know what case this is.

AHS
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Passing a Method Name to a Method, Redux Gene Wirchenko Java 51 07-24-2011 10:02 AM
Passing method name to method? Arfon Smith Ruby 3 09-28-2007 03:38 PM
adding a variable name to a hash to name is part of the variable name Bobby Chamness Perl 2 04-22-2007 09:54 PM
print("my name is {name}, and {age}-year old {gender}", name, age, gender); =?iso-8859-1?B?bW9vcJk=?= Java 7 01-02-2006 04:39 PM
Re: Urgent! how to get object name, method name and attribute name based on the strings? ding feng C++ 2 06-25-2003 01:18 PM



Advertisments