aspose file tools*
The moose likes Java in General and the fly likes Can Varible be used to create a Method ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Can Varible be used to create a Method ?" Watch "Can Varible be used to create a Method ?" New topic
Author

Can Varible be used to create a Method ?

Manu Garg
Greenhorn

Joined: May 29, 2008
Posts: 17
Hi All,

I know this might sound wierd but I am trying to figure out some thing. here is an example.
class test1{
private String s;
public String getName(){
return "Hello";
}
}

class test2{
public static void main(String args[]){
String Str = "getName";
test1 tst = new test1();
System.out.println("tst."+Str+"()");
//Is it possible to make the System.out.println print Hello or if there any other way to do the same. If yes please suggest me how to acheive it
}
}

Thanks,
MG
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

"Manu",
Welcome to JavaRanch!

We're pleased to have you here with us here on the ranch, but there are a few rules that need to be followed. One is that proper names are required. Please take a look at the JavaRanch Naming Policy and adjust your display name to match it.

In particular, your display name must be a first and a last name separated by a space character, and must not be obviously fictitious. Initials are OK for the first and middle names but not the last. You can change it here
[ May 29, 2008: Message edited by: Ben Souther ]

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

You might want to look into the "Command Pattern" which allows you to determine which object's methods to call at run time using a string.
[ May 29, 2008: Message edited by: Ben Souther ]
Manu Garg
Greenhorn

Joined: May 29, 2008
Posts: 17
Not aware of this "Command Pattern" can you brief me about it ?
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Yes, but can you please read my earlier post about the naming convention a little more carefully?

BTW: Thanks for changing it so quickly.

-Ben
Manu Garg
Greenhorn

Joined: May 29, 2008
Posts: 17
Let me explain you what I am trying to acheive here.
I am using SAX parser to parse a XML document.

package com.tr.events;

import java.util.HashMap;
import com.tr.properties.*;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;



public class AltandElmtFormatter extends DefaultHandler implements
org.xml.sax.ContentHandler {

private StringBuffer sb = new StringBuffer();
HashMap stockTicker = new HashMap();
private String currentElement = "";

private String[] elements;
private String[] attributes;
private eventApi evnts;

AltandElmtFormatter()
{
String xmlElmts = EventProperties.getProperty("eventElm");
System.out.println("Properties retrived" +xmlElmts);
elements=xmlElmts.split(",");
}

private String exchange = "";

public void characters(char[] ch, int start, int length) {

String value = new String(ch, start, length);

if (!value.trim().equals("")) {
currentElement="getDate";
String test="evnt"+"."+currentElement+"()";
System.out.println("evnt"+"."+currentElement+"()");

// I don't want to specify each and every attribute and elements in if statment and get the values for them. I need some dynamic mechanism which get populate the object based on the attribute or element name is there any way to do that.

if (currentElement.equalsIgnoreCase("Trade")) {


}

if (currentElement.equalsIgnoreCase("Change")) {

}

if (currentElement.equalsIgnoreCase("High")) {


}
if (currentElement.equalsIgnoreCase("Low")) {

}

if (currentElement.equals("FiftyTwoWeekHigh")) {

}

if (currentElement.equalsIgnoreCase("FiftyTwoWeekLow")) {

}

if (currentElement.equalsIgnoreCase("PreviousClose")) {

}
if (currentElement.equalsIgnoreCase("Volume")) {

}

}

}

public void endElement(String namespaceURI, String localName, String qName) {

//That means add StockQuote to HashMap
//log.debug("End Event-----> "+qName);
if (qName.equalsIgnoreCase("Event")) {
System.out.println("completed creating one object");

}
}

public HashMap getStockTicker() {
return stockTicker;
}

In startElement I am getting the values from .properties file

public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) {
Attributes attrs = atts;


//System.out.print("[" +qName +"]");

for(int i=0;i<elements.length;i++)
{
if(qName.equalsIgnoreCase(elements[i]))
{
if(qName.equalsIgnoreCase("Event"))
{
//Create New Object of type event
evnts = new eventApi();
}
if(attrs!=null)
{
try
{
String []attribute = EventProperties.getProperty(elements[i]).split(",");
System.out.print("Element " +elements[i]);
for(int it=0;it<attribute.length;it++)
{

for(int ip=0;ip<attrs.getLength();ip++)
{
if(attribute[it].equalsIgnoreCase(attrs.getQName(ip)))
{
System.out.print( " " +attribute[it]+",");
currentElement=attribute[it];
}
}
}
System.out.println();
}
catch(Exception e){
}
}
}
}
}


}

Any help will be appreciated.
Manu Garg
Greenhorn

Joined: May 29, 2008
Posts: 17
Ben,
I didn't got any link
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Sorry about that.
http://en.wikipedia.org/wiki/Command_pattern


Again, thanks for fixing your name.... but.
Initials are allowed for the first or middle names but not the last.

If you wouldn't mind fixing it, one more time...

Thanks.
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Here's a quick and dirty example of the command patter that I threw together.

[ May 29, 2008: Message edited by: Ben Souther ]
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Looking at what you're trying to do, I think this pattern would work for you.

Rather than trying to call methods by name (like functions) retrieve objects, by name from a map and then call their exec() method.
Manu Garg
Greenhorn

Joined: May 29, 2008
Posts: 17
Thanks Ben,

This means I will have to create classes equal to number of Attribute and/or elements there are in the XML file..Thanks for suggestion. Will keep looking for the other suggestion too.
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Originally posted by Manu Garg:
Thanks Ben,

This means I will have to create classes equal to number of Attribute and/or elements there are in the XML file..Thanks for suggestion. Will keep looking for the other suggestion too.


You were going to create methods equal to the number of attributes/elements, anyway, right? Is it that much more work to wrap each function in a class declaration?
Manu Garg
Greenhorn

Joined: May 29, 2008
Posts: 17
Make sense. I will work on this suggestion thanks again
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

You can call methods by name using the java.util.reflect package. See, for example, http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html .


[Jess in Action][AskingGoodQuestions]
Manu Garg
Greenhorn

Joined: May 29, 2008
Posts: 17
Hi Ben,

Since we are using 1.4
Map<String, Command> commands = new HashMap<String, Command>();
this won't work will have to find some other alternative

Thanks
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

You can look at using reflection, as Earnest has suggested.

You can also use the command pattern without generics.
You'll just need to cast the objects to "Command" as you retrieve them from the map. (The command pattern was being used long before Java had generics).


[ May 30, 2008: Message edited by: Ben Souther ]
Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
Originally posted by Manu Garg:
Hi Ben,

Since we are using 1.4
Map<String, Command> commands = new HashMap<String, Command>();
this won't work will have to find some other alternative

Thanks



Simply remove the "generics" (which were, of course) added in 1.5 = Java5



Also, when posting code, select the code, and click the "CODE" button beneath the editing area. (You can do this retroactively by clicking on the Edit Button (pencil and paper)).
[ May 30, 2008: Message edited by: Bill Shirley ]

Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
 
jQuery in Action, 2nd edition
 
subject: Can Varible be used to create a Method ?