Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Concatinating strings to equal function name and calling it 2

Status
Not open for further replies.

1DMF

Programmer
Jan 18, 2005
8,795
GB
Hi,

I was wondering if it is possible to concatenate a string with an integer variable, and then execute it as the name of a function to call?

So if I had some code which simulated a dice and so there were six different methods names face1,face2... etc.

if I randomly chose a number from 1-6 and stored it in iRoll, can i then simply concatenate the literal string "face" with iRoll and then run it as the method to call?

Cheers,
1DMF



"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

Google Rank Extractor -> Perl beta with FusionCharts
 
Is it possible? Yes, it's called reflection
Is it a good idea? I don't thin so. Reflection has a poor performance and it's difficult to read or maintain.

A switch/case clause would do the trick

Cheers,
Dian
 
Here's a quick code snippet that should get you on the right track..

Code:
// we assume that called methods have no argument
Class params[] = {};
Object paramsObj[] = {};

// get the Class
Class thisClass = Class.forName(aClass);
// get an instance
Object iClass = thisClass.newInstance();
// get the method
Method thisMethod = thisClass.getDeclaredMethod(aMethod, params);

// call the method
thisMethod.invoke(iClass, paramsObj).toString() // or something
 
Is it possible? Yes, it's called reflectionIs it a good idea? I don't thin so. Reflection has a poor performance and it's difficult to read or maintain.A switch/case clause would do the trick

hmm really, taking a string and saying call the function relative to the value of the tring has a performance issue over calling the funcion, how so?

I know there is if/switch, though for the course work we werent allowed to use switch, as it hasn't been taught to use yet.

I used if statements for the course work, and I actually lost a mark for not nesting the darn things, but in perl I most certainly would use the method I describe.

how is
Code:
invoke("face"+iNum);
a bad thing, if I understand what Mikey has said.

Basically you can call a method that is represented by a string using invoke, is that right?

do you have to put .toString() on the end or is that assuming there is a message answer that will be converted to a string?



"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

Google Rank Extractor -> Perl beta with FusionCharts
 
looking further I don't think I want reflection. It appears to be an API.

I just want to call an already exisiting method from within a class method in the same class, based on the value of a string.

How hard can it be?

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

Google Rank Extractor -> Perl beta with FusionCharts
 
Java is an object-oriented language, not a script language so no, you cannot call a method dinamycally at runtime.

And talking about performance, the main reason is that you have to link the method at runtime rather than at compile time, take a look at this

Btw, you should post things like "I cannot use a switch/case", we're used to give the best solution to a problem without that kind of non-smart requirements

Cheers,
Dian
 
Thanks Dian,

It's certainly hard to stop thinking in certain ways when you are so used to procedural scripting languages.

Though I am still finding this concept of not being able to dynamically do stuff hard to get my head round, why can you do some stuff dynamically at run time but not other stuff.

you create the objects and classes on the fly at runtime, yet something as simple as calling a method via the value of a string isn't possible.

I can accept if this isn't possible, but I will never be able to understand why!




"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

Google Rank Extractor -> Perl beta with FusionCharts
 
One of the rules of this forum is that there should be no postings for the solving of classroom assignments...
and if you haven't been told about 'switch' (about chapter 3 of your course, I presume), then why are you (even) taking the route of reflection, that is somewhere around chapter 25 or so, and you should have never heard of it in the first place? That's Advanced Java, so not for beginners!
 
I think you are missing the point TonHu,

No where here did I ask help for anything to do with my course, I've been around these forum long enough to know the rules.

I'm not sure what chapers you are talking about, they have no resemblence to anything i'm studying, i'm currently on unit 7 if you must know.

I came here as an IT professional asking a simple question whether it was possible to call a function where the name of the function to call was stored in a variable.

As you clearly pointed out, reflection is advanced, I am not, and reflection was not even something I asked about.

Please show me where I requested information about reflection?, I think you will find Dian suggested it as a possible solution to my question, so how on earth is this related in any way shape or form to my current course, do you even know what course or qualification I am studying?

I would appreciate you not spreading lies about myself and my posts, I have been a devout user of TT for many years, I have written FAQ's for TT and I continue to participate and support TT, all within the guidelines and rules of this forum.

If you have nothing truthful or civil to say, please do not reply to my threads!

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

Google Rank Extractor -> Perl beta with FusionCharts
 
@1DMF: It's not a personal attack, even if you might feel it that way. It just that such questions can very easily be asked on google, and found pretty good samples. This is, as you state, a forum of pro's, not a shoutbox.
 
1DMF

What you are proposing here is the Java equivalent of using eval in a scripting language (which as you can see, attracts the same levels of derision here as we would normally give it on the Perl forum [smile] ). There is usually a better solution - in your example you'd probably go with a Dice class that has a method face(n) that takes an integer from 1-6 as a parameter. Then you wouldn't need to catenate strings and integers to get the method name, you'd just invoke it with your integer as a parameter.

But that doesn't help you here, as you have a particular problem to solve. With a compiled language you are trading ease of coding for execution speed, at the cost of a little flexibility. As you haven't learned switch yet, it sounds like you are going to have to go with a bunch of nested if statements. It is possible that they are going to introduce switch in the next chapter to show you how much easier it is...

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
If the switch statement (still) can't be used, then..........
 
Thanks Steve,

I still feel everyone is missing the point.

I don't need help solving a problem, as for the actual course, it's done, i've been marked, I got 98%.

I was simply asking a question regarding if something was possible or not, nothing more, nothing less.

As for your method signature Steve, it wouldn't work, not the way the assignment had already made you write six different methods called face1,face2,face3 etc...

which took no argument and didn't return a message answer either. it simply updated the graphic display to show the relevant number (blobs) on the die face.

in that situation, where the methoid that produces the random number for the dice roll, which then has to say if it's 1 call face1 , if it's 2 call face 2 etc..

it is logical to concatenate the string 'face' with the random number integer variable and call the result as a function name.

switch, case, if-then-else-elseif or any other method is just superflous code and a waste of time if you can achieve the goal in the manner I describe.

Maybe in the perl forum people would disagree, and suggest the use of a case/switch statement, but if it was possible to achive it the way I describe , that is how I would do it.

Whether people agree or not, it's how I would do it, to me, it makes more logical sense than writing nested if's , case/switch statements or anything else. But of course your milage may vary.

I never for one minute thought such a simple question would cause so much controvecy.

Tonhu

One of the rules of this forum is that there should be no postings for the solving of classroom assignments...

well seings as I didn't ask a question for solving a classroom assignment, of course it was a pesonal attack accusing me of doing something that I did not.

I am fully aware of the rules and also how Google works, I suggest you use it to look up what 'false accusation' means!!!

Google is not my friend, I choose my friends, not my search engine!




"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

Google Rank Extractor -> Perl beta with FusionCharts
 
They marked you down 2%? For what? [smile]

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
1 mark was for not going into enough detail on one of my explinations and the other was for not nestng the if statements for the method that calls the face methods.

Part of the specification when answering has been emphasised that easily readable code and 'ease of maintenance' is a high priority.

As it's part of the concept of OO design and coding.

because I wrote six separate if statements and didn't nest them, it meant each conditional statement would be checked even if the one condition which resulted as true and called the required face method had already been executed.

But I took the view that the overhead of checking 6 if statements was negligable against the ease of reading the code and maintaining it.

Trying to 2nd guess the way they expect the answer to be written isn't easy, I made a descision based on their guidelines and it cost me a mark!

as we all know the bottom line is you wouldn't use a bunch of if statements in the first place, but as that is what was required, I think it is easier to read 6 seperate if statements against them being nested or even nested with 'else if' and trying to match up the curly braces.

hey ho, 98/100 isn't bad wouldn't you say! ,so i'm not going to loose any sleep over it ;-)

the next assignment has to be in on 28th Jan , so it will be interesting to see if I can keep my percentages as high throughout the entire course.

At least it looks like i'll be obtaining a pass, as long as I don't balls the actual exam up! [lol]

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

Google Rank Extractor -> Perl beta with FusionCharts
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top