Calling a method with a string

Here's the question:
I want to call a method with the name equal to a string variable.
For example, if the string variable contains "hellojava" , i'd like the hellojava() method to be called..
if the string contains "error", the error() method should be called..
and so on..:)

Here is an example I had thrown together for this
purpose of the exact demonstration, Ar'nt you in luck.:-). If there is anything you don't understand,
I can be reached at [email protected] and will be happy to help....
import java.lang.reflect.*;
import java.io.*;
class Test {
     String name = "Default";
        public Test(String name) {
                this.name = name;
        public void test() {
                System.out.println("Hello");
     public void count() {
          for(int i=0; i<10; i++) {
               System.out.println(i);
       public static void main(String[] args) {
             try {
                     Test myObject = new Test("test1");
                         Class myClass = myObject.getClass();
               BufferedReader bRead =
                    new BufferedReader(
                    new InputStreamReader( System.in ));
               String bufStr = null;
               while( (bufStr = bRead.readLine()) != "exit") {
                     Method noParams = myClass.getDeclaredMethod(bufStr, new Class[] {});
                          noParams.invoke(myObject, new Object[] {});
            }catch(Exception e) {
               System.out.println("No Such Method.");
}Good Luck,
-- Ian

Similar Messages

  • Calling a method with parameters in jstl?

    i need to call a method with a series of String parameters what am i doing wrong?
    the java
        public ArrayList getEmployeeSkills(String ename, String snmae, String yearsexp)the jstl
        <jsp:useBean id="empskill" class="com.Database.EmployeeSkill"/>
        <c:forEach var="emp" items="${empskill.EmployeeSkills(null, null, null)}">
        </c:forEach>

    this works:
         <jsp:useBean id="empskill" class="com.Database.EmployeeSkill" scope="page">
             <jsp:setProperty name="empskill" property="ename" value="Helen Smith"/>
             <jsp:setProperty name="empskill" property="sname" value="Java"/>
         </jsp:useBean>but this part isnt:
         <c:forEach var="empskill" items="${empskill.EmployeeSkillsReport}">
         </c:forEach>ive removed the get part from the method as i have done before from the java class it is calling:
    public ArrayList getEmployeeSkillsReport()
    but it produces:
    org.apache.jasper.JasperException: Exception in JSP: /main.jsp:146
    143:      </jsp:useBean>
    144:      
    145:
    146:      <c:forEach var="empskill" items="${empskill.EmployeeSkillsReport}">
    147:      </c:forEach>
    148:                          
    149:    
    Stacktrace:
         org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:506)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    javax.servlet.ServletException: An error occurred while evaluating custom action attribute "items" with value "${empskill.EmployeeSkillsReport}": Unable to find a value for "EmployeeSkillsReport" in object of class "com.Database.EmployeeSkill" using operator "." (null)
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:843)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:776)
         org.apache.jsp.main_jsp._jspService(main_jsp.java:244)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:334)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    javax.servlet.jsp.JspException: An error occurred while evaluating custom action attribute "items" with value "${empskill.EmployeeSkillsReport}": Unable to find a value for "EmployeeSkillsReport" in object of class "com.Database.EmployeeSkill" using operator "." (null)
         org.apache.taglibs.standard.lang.jstl.Evaluator.evaluate(Evaluator.java:109)
         org.apache.taglibs.standard.lang.jstl.Evaluator.evaluate(Evaluator.java:129)
         org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager.evaluate(ExpressionEvaluatorManager.java:75)
         org.apache.taglibs.standard.tag.el.core.ForEachTag.evaluateExpressions(ForEachTag.java:155)
         org.apache.taglibs.standard.tag.el.core.ForEachTag.doStartTag(ForEachTag.java:66)
         org.apache.jsp.main_jsp._jspx_meth_c_forEach_3(main_jsp.java:590)
         org.apache.jsp.main_jsp._jspService(main_jsp.java:232)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:334)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

  • Dynamic Imagelink Component - Calling Impl method with input parameter

    Hi All,
    I have requirement where Imagelinks are created dynamically on the pageload. Generated the components and the components are displayed on the jspx.
    Now when I click the image link, a method in AMImpl should invoke and this method takes some input parameters.
    I am able to call the method successfully in AMimpl with the help of below code. But I could not understand how to pass the input parameters to that method.
                               RichCommandImageLink lockimageLink =
                                new RichCommandImageLink();
                            lockimageLink.setIcon("icon.png");
                            lockimageLink.setId("icon" + index);                   
                            MethodExpression me =
                                JSFUtils.getMethodExpression("#{bindings." +
                                                             "MyMethodName" +
                                                             ".execute}");
                            lockimageLink.addActionListener(new MethodExpressionActionListener(me));
      public static MethodExpression getMethodExpression(String name) { 
       Class [] argtypes = new Class[1]; 
       argtypes[0] = ActionEvent.class; 
       FacesContext facesCtx = FacesContext.getCurrentInstance(); 
       Application app = facesCtx.getApplication(); 
       ExpressionFactory elFactory = app.getExpressionFactory(); 
       ELContext elContext = facesCtx.getELContext(); 
       return elFactory.createMethodExpression(elContext,name,null,argtypes); 
      } Can some one please suggest how to pass input parameters to the Impl method.
    Jdeveloper Version : 11.1.1.4.0
    Thanks,
    Morgan.
    Edited by: 900114 on May 12, 2012 11:23 PM

    You can use the below method to call an AMImpl method. You can pass parameters as well to the AMImpl method.
    DCBindingContainer bindings = getDCBindingContainer();
    OperationBinding ob = bc.getOperationBinding("MyMethodName");
    Map m = ob.getParamsMap();
    ob.put("paramName", "paramValue"); paramName is the parameter in AMImpl and paramValue is the value to be passed.
    ob.execute();
    Where getDCBindingContainer() is:
    public DCBindingContainer getDCBindingContainer() {
    ExpressionFactory exprFactory;
    ELContext elContext;
    ValueExpression valueExpression;
    DCBindingContainer dcBindingContainer;
    FacesContext facesContext = FacesContext.getCurrentInstance();
    exprFactory = facesContext.getApplication().getExpressionFactory();
    elContext = facesContext.getELContext();
    valueExpression =
    exprFactory.createValueExpression(elContext, "#{bindings}",
    Object.class);
    dcBindingContainer =
    (DCBindingContainer)valueExpression.getValue(elContext);
    return dcBindingContainer;
    Hope this helps
    Edited by: umesh.agarwal on May 13, 2012 12:10 AM
    Edited by: umesh.agarwal on May 13, 2012 12:10 AM

  • Call a method with complex data type from a DLL file

    Hi,
    I have a win32 API with a dll file, and I am trying to call some methods from it in the labview. To do this, I used the import library wizard, and everything is working as expected. The only problem which I have is with a method with complex data type as return type (a vector). According to this link, import library wizard can not import methods with complex data type.
    The name of this method is this:   const std::vector< BlackfinInterfaces::Count > Counts ()
    where Count is a structure defined as below:
    struct Count
       Count() : countTime(0) {}
       std::vector<unsigned long> countLines;
       time_t countTime;
    It seems that I should manually use the Call Library Function Node. How can I configure parameters for the above method?

    You cannot configure Call Library Function Node to call this function.  LabVIEW has no way to pass a C++ class such as vector to a DLL.

  • Calling a method with a html Submit button

    hi guys,
    is it possible to call a method from a JSP file using a HTML submit button. I know i can call another website easily doing it this way, is there a similar way available to call a method once the button is clicked?
    FYI
    The method is in a bean file named jdbc. The methods name is getUsername.
    Nice one.
    <form action = <%jdbc.getUsername()%> <input type="submit" value="Submit">

    Dear friend,
    you mentioned that u need to call a method when submit button is clicked. Is the method dynamically created. If not so, then you can include the method on the submit button html file itself.
    Regards,
    Rengaraj.R

  • Using Java Reflection to call a method with int parameter

    Hi,
    Could someone please tell me how can i use the invoke() of the Method class to call an method wiht int parameter? The invoke() takes an array of Object, but I need to pass in an array of int.
    For example I have a setI(int i) in my class.
    Class[] INT_PARAMETER_TYPES = new Class[] {Integer.TYPE };
    Method method = targetClass.getMethod(methodName, INT_PARAMETER_TYPES);
    Object[] args = new Object[] {4}; // won't work, type mismatch
    int[] args = new int[] {4}; // won't work, type mismatch
    method.invoke(target, args);
    thanks for any help.

    Object[] args = new Object[] {4}; // won't work, type
    mismatchShould be:
        Object[] args = new Object[] { new Integer(4) };The relevant part of the JavaDoc for Method.invoke(): "If the corresponding formal parameter has a primitive type, an unwrapping conversion is attempted to convert the object value to a value of a primitive type. If this attempt fails, the invocation throws an IllegalArgumentException. "
    I suppose you could pass in any Number (eg, Double instead of Integer), but that's just speculation.

  • Calling arbitrary method with expression language

    I'm new to JSP, but have a strong background in Java. I've created a bean that I've included on a JSP page that is meant to manage access to a database. On this bean I have a method
    public int createNewRecord();which will create a new record and return its id. I then want to embed this id in a link within my webpage by using something like:
    <jsp:useBean id="dbBean" scope="application" class="com.myDomain.DatabaseIfaceBean"/>
    <html>
    <body>
    Link to <a href="relativePage.jsp?recordId=${dbBean.createNewRecord}">record page</a>
    </body>
    </html>However, this doesn't work. Is there a way to call this method? If this method accepted arguments, is there some way I could pass arguments to it?

    Its a bit long winded, but EL functions would be the way to go. [url http://www.sitepoint.com/article/java-6-steps-mvc-web-apps/6]Here's  a link (search for EL functions in the page)
    ram.

  • Calling CFC Method With AJAX

    Hello Guys , I am trying to call Component method using AJAX
    but its not working , Here is the Code i am using . In Code
    REC.OPEN is giving Trouble. Is this a Proper way to call Function ?
    function Process_Calendar(day,month,year,name){
    var hello = document.getElementById(name);
    hello.innerHTML = day+'<img
    src="../../Content/Graphics/images.jpg">';
    if (window.XMLHttpRequest)
    req = new XMLHttpRequest();
    else if (window.ActiveXObject){
    req = new ActiveXObject("Microsoft.XMLHTTP");
    req.open("getNoCache","BaseFunc.cfc?Method=Insertme&month="+month+"&day="+day+"&year="+ye ar+"&ms="+new
    Date().getTime(),true);
    req.send("");
    if ((req.readyState == 4) && (req.status == 200)){
    var arr = req.responseText;
    hello.innerHTML = arr;
    Thanks a Lot

    This might be a stupid question, but do you have the method's
    access set to
    remote? You are calling it via HTTP.
    Bryan Ashcraft (remove brain to reply)
    Web Application Developer
    Wright Medical Technologies, Inc.
    =============================
    Macromedia Certified Dreamweaver Developer
    Adobe Community Expert (DW) ::
    http://www.adobe.com/communities/experts/
    "flooker" <[email protected]> wrote in message
    news:e61jtu$o22$[email protected]..
    > Hello Guys , I am trying to call Component method using
    AJAX but its not
    > working , Here is the Code i am using . In Code REC.OPEN
    is giving
    > Trouble.
    >
    > function Process_Calendar(day,month,year,name){
    >
    > var hello = document.getElementById(name);
    > hello.innerHTML = day+'<img
    src="../../Content/Graphics/images.jpg">';
    >
    > if (window.XMLHttpRequest)
    > {
    >
    > req = new XMLHttpRequest();
    > }
    > else if (window.ActiveXObject){
    >
    > req = new ActiveXObject("Microsoft.XMLHTTP");
    >
    > }
    >
    >
    >
    >
    req.open("getNoCache","BaseFunc.cfc?Method=Insertme&month="+month+"&day="+day+
    > "&year="+year+"&ms="+new Date().getTime(),true);
    > req.send("");
    >
    > if ((req.readyState == 4) && (req.status ==
    200)){
    > var arr = req.responseText;
    > hello.innerHTML = arr;
    >
    > }
    > }
    >
    > Thanks a Lot
    >

  • Call applet method with javascript

    my html - code:
    <APPLET NAME="Mail" ... ... ></APPLET>
    <form action="javascript:document.applets("Mail").test("Execute JAVA Applet Function")">
    <input type="submit" value="Execute Applet Function">
    </form>
    my applet code:
    public void test(String t)
    {System.out.println("executing test()");
    teststr = t;
    repaint();
    in the paint() method i draw the teststr with Graphics.drawString - but nothing happens...
    any suggestions?
    thx

    Directly calling a Java Applet's public method from within
    JavaScript is made possible by LiveConnect which is not implemented by Internet Explorer as of yet. LiveConnect is only available on Netscape navigator at this time.

  • Call applet method with arguments from JavaScript

    I have an applet with a method doSomething(int a, String b, double c), I want get a,b,c from threee text fields put into an HTML page, and pass them to the applet method. I've a very poor knowledge in JavaScript, how can I pass correctly the arguments without raise a CastException? It seems to me that JavaScript doesn't have int, String, double.....

    Hi!
    You can verify before you send the parameters to the applet
    Something like that:
    var result = parseInt (a);
    if (result =NaN)
    alert("Sorry not Int");
    return false;
    and after that you can send the parammeters to the applet that way:
    document.yourApplet.Your_function_from_applet(result,..)
    hope this help!
    adina

  • Easy Question, 'calling' a method with a number

    Here is a bit of code
    public class RollDice {
        public int x = 0;
        public RollDice(byte numberOfDice) {
            x = numberOfDice;
    }and another bit...
    public class RollDiceDemo {
        public static void main(String[] args) {
            RollDice currentRoll = new RollDice(7);
            System.out.println("Width of rectOne: " +
                    currentRoll.x);
    }So my issue is this, the code works if I change byte to int in 'public RollDice(byte numberOfDice) {' and I am guessing that is because ''7' defaults to an int in the call statement. How do I tell it to be a byte, I've tried RollDice(byte 7) with no luck.

    Encephalopathic wrote:
    MajorApus wrote:
    Because I am a newbie? What should I be doing instead?The class field "x" is an int. Why not use an int parameter in the constructor? What advantage is there to use a byte here?You realise now OP will just change x to be byte as well.

  • How to do this: Link which calls a methode with a parameter?

    Hello!
    I have a small question:
    I have a jsp-site with some beans.
    On the jsp-site I have the following code which isnt functional:
    <c:forEach items="${filter.resultlist}" var="result">
        <c:url action="#{filter.selectedAoid(result.aoid)}">
             <c:out value="${result.name}" / >
         </c:url>
    </c:forEach>-> As you can see:
    I want to make a Link, which is named like the String in the List and accessable by ${result.name} and on a click it should run "filter.selectedAoid()" with an int Parameter.
    (So I can access the right object with my Aoid-identifier...)
    The List comes from a DB and I am able to access the values of the Objects in the list.
    Could someone please tell me how that is done?
    Thanks in advance
    Fuchur

    One way of hacking this problem is by dynamically updating the job step which executes the stored procedure to include the parameters the user provided.  You can do so by using
    msdb.dbo.sp_update_jobstep.
    So for example, you could create a job named "Test job" and in that job the first step would be to execute your stored procedure.  You would then use the following code to update that step at run time:
    execute msdb.dbo.sp_update_jobstep
    @job_name = N'Test job',
    @step_id = 1,
    @command = 'execute my_proc @my_variable = ''my_value'''
    You'd then use sp_start_job like so:
    execute msdb.dbo.sp_start_job @job_name = 'Test job'
    Your job would then execute using the value provided at run time for the @my_variable parameter.

  • Calling FP Methods with Javascript

    I'd like to be able to jump to specific pages in my
    flashpaper document using an html / javascript link. My javascript
    function setThePage gets a page number from the HTML link and feeds
    the value to the flash file (which my flashpaper movie clip loads
    into). That value is then dumped into a function that eventually
    sets the setThePage value equal to setCurrentPage, which is listed
    in the flashpaper API as the function that changes the current
    page. I've had no luck. I'm getting a javascript error telling me
    the object doesn't support the method or function and I think it
    has to do with the setCurrentPage function only working on the load
    of the flashpaper swf. Does anyone have a different solution for
    using html links to jump to specific flashpaper pages?

    Rich,
    I am interested in doing similar things from within a
    FlashPaper document loaded into my Flash movie. I wish to create
    links within the FlashPaper doc. that will talk to Actionscript in
    the main movie. I know that using the Flash 8 ExternalInterface
    Class is key, but in creating links in a Word Doc that eventually
    becomes FP, I haven't a clue. It's easy enough to create links that
    navigate to other URLs, or with the same page, but with the parent
    Flash movie...
    Anyway, if you have discovered anything, please share. I will
    also, should I discover anything. Thanks, Mike.
    mailto:[email protected]

  • Calling HTTP Service with Query string in Orchestration

    Hi,
    I have to BTS orchestration as a service to my end user. In Orchestration i have to call "http://abc.net/.xyz?a=101&b=102" service and response send to end user. a and b values are to be passed by end user system.Could you please help me how
    to work on this requirement

    When you use querystring in your URL, then your are not calling a webservice. You need a non-SOAP
    adapter.
    Best bet for you is to use
    REST (WCF-WebHttp) adapter if you use BizTalk Server 2010 R2 or more. Otherwise
    webHttpBinding with WCF-Custom
    For use BizTalk Server 2010 R2 or more:
    http://blogs.biztalk360.com/rest-wcf-webhttp-adapter-in-biztalk-server-2010-r2/
    You can use webHttpBinding (that supports consuming and exposing ReSTful services) available with WCF-Custom adapter can send non-SOAP
    messages. Refer this article for more info:
    https://social.technet.microsoft.com/wiki/contents/articles/2474.invoke-restful-web-services-with-biztalk-server-2010.aspx
    If this answers your question please mark it accordingly. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply.

  • Rhino calling overloaded Java methods with Array parameters

    Has anyone had any problems writing JavaScript code that calls overloaded Java methods?
    I have two Java defined methods that differ in the arguments, one takes a string the other takes an array of strings. The problem is calling Java methods within the JavaScript always calls the method with the String argument...
    /* Java Code Here */
    public void function(String s) { /* Function A */ }
    public void function(String[] sa) { /* Function B */ }
    /* JavaScript  Code Here */
    param = java.lang.reflect.Array.newInstance(java.lang.String, 2);
    param[0] = "test";
    param[1] = "test2";
    stringParam = "test3";
    /* Both function calls below end up calling the Function A from above */
    function(param);
    function(stringParam);PS...in case you're not familiar with Rhino,
    It is a mozilla package that embeds a JavaScript interpreter within a Java application...
    http://www.mozilla.org/rhino/

    haha...I can't even find my other thread :(
    Sorry about the double post...I'll go look for my other thread now

Maybe you are looking for

  • Audit Trail on R12.1 (shadow table concept)

    I want to enable Audit Trail at table (column) level. Though I got response from Oracle Support but at present I am stuck on particular error. Here are the steps which I followed: 1. Apply latest Patch 12860752:R12.FND.B - Latest Audit Trail Fixes fo

  • How to call servlet from jsp

    i m trying to call it from jsp using <a href="../purchaseP?orderno=<%=pno%>"><%=pno%></a> but its giving error.. type Status report message HTTP method GET is not supported by this URL description The specified HTTP method is not allowed for the requ

  • Unexpected problem with this printable

    Started by trying to stop the printing of the "Samples" printable that was acquired accidentally.  Tried directions found in the forums to no avail.  Tried through the HP Go manageprint route and never saw the minus sign in the printable header as de

  • 2 Devices in Fatal1ty

    Hey, is it anyhow possible to connect 2 devices to sound card? (only fatalty pro) I mean repro + headset

  • Security settings STILL failing

    i've posted about this many times with increasing anger. i've only had one response, altho repeatedly, which told me (also repeatedly) a "fix" that (also repeatedly) never worked. i am getting SICK of skype claiming to have decent security measures,