Calling a method via String representation of instance

Is it possible to call a method of a specific (and already existing) instance of a class using a string representation of the instance?

By "String representation of an instance," I simply mean a string that has the same format as a normal method call would have. So where a method would normally be called like this:
ClassX itsInstance = new ClassX();
itsInstance.methodX();
The string representation would be:
String instanceName = "itsInstance";
And there would be some way of using this string to call the method referred to by instanceName.
The idea here is that I want to use the existing instance, whereas using reflection, as below, would create a new instance:
String className = "X";
String methodName = "print";
Class xClass = Class.forName(className);
Method xMethod = xClass.getMethod(methodName,null);
Object object = xClass.newInstance();
xMethod.invoke(object,null);

Similar Messages

  • Calling a method via invokeMethod (JDI)

    Hi !
    Does anybody know how to invoke a method
    via the invokeMethod method of the Java Debug Interface (JDI).
    This suspends the execution of the program !
    I've read somewhere that the vm must be resumed,
    but I don't see how, as a vm.resume() after the
    invocation is never reached !
    Thanx for any help !
    Alex

    I have the same problem ..Null pointer exception thrown. here is my sample code that I did:
    public void methodExitEvent(MethodExitEvent event)
    ObjectReference obj = objectReference(event);
    if(obj!=null && !event.method().name().equals("<init>"))
    System.out.println(" Leaving the method " + event.method().name() + "() Object " + obj.hashCode());
    List objMethodsList= event.method().declaringType().methodsByName("methodA");
    Method emptyState= (Method)objMethodsList.get(0);
    //ClassType myClass= (ClassType)obj.referenceType();
    //Method emptyState= myClass.concreteMethodByName("methodA","()V");
    try
    Value myValue= obj.invokeMethod(event.thread(), emptyState ,null,ObjectReference.INVOKE_SINGLE_THREADED);
    catch(Exception e)
    e.printStackTrace();
    System.out.println("Error in invoking method "+e.getMessage());
    else if(obj!=null && event.method().name().equals("<init>"))
    System.out.println("Object " + obj.hashCode()+" END its life");
    and here is the trace that i got from the exception thrown:
    java.lang.NullPointerException
    at com.sun.tools.jdi.MirrorImpl.validateMirrorsOrNulls(MirrorImpl.java:8
    2)
    at com.sun.tools.jdi.ObjectReferenceImpl.invokeMethod(ObjectReferenceImp
    l.java:355)
    at EventThread.methodExitEvent(EventThread.java:186)
    at EventThread.handleEvent(EventThread.java:69)
    at EventThread.run(EventThread.java:35)
    Error in invoking method null
    Need help ASAP especially those of you who have created debugger. Im trying to create a tracer and try to invoke the method of the debugee object....

  • How to get exit code from C code when calling java method via JNI?

    Hi, All
    in my project, i need to call a java method from C code using JNI, yet I do
    not know how to
    retrieve the exit code of java program. the java code is like below
    public static void main(....)
    if(error){
    System.exit(-77);// the exit code is -77
    and the JNI c code may like below
    /* Invoke main method. */
        (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
    //here I want to retrieve the exit code from java to check if there is an
    error
    any suggestions? thanks

    Hi Liang Zhang,
    In your C code add:
    void (JNICALL y_exit)(jint code) {
    and when you are initialazing JVM options add:
    JavaVMOption options[...];
    options[...].optionString = "exit";
    options[...].extraInfo    = y_exit;
    See http://java.sun.com/j2se/1.3/docs/guide/jni/jni-12.html
    Best regards, Maksim Rashchynski.

  • Detecting static calls in methods via Class.forName(...)

    Hi!
    I'm trying to detect, if a method (or a contructor) of a Class object, loaded by Class.forName(...) contains a static call like System.out.println( "some text" );
    I need it to figure out if (in this case above) the class "System" is needed for running this example class.
    I don't have the source code (and don't want it anyway) to write a parser for it. I just want to extract this single information: Is there a method/contructor in the given class containing static calls by any other classes and what's the the of these classes?
    Anybody an idea?
    Thoto

    I'm trying to detect, if a method (or acontructor)
    of a Class object, loaded by Class.forName(...)
    contains a static call like System.out.println("some
    text" );BCEL should be able to do this.But I need to do that in my own program.
    System.out.println() is not a static method.That's right. If it's static or not doesn't really matter, it's just the information WHICH class is embedded into this call. It could also be a call like
    int i = Integer.MAX_VALUE.I just need (in that case) the informatation that the class "Integer" is needed to proceed that call.
    You can use javap to find this, or the BCEL library.I already did that with javap. But it's useless for me, I need it in my own program. I don't want to decompile some program. I have no illegal intentions in hacking or so. It's for my own programs, but I don't want to scan the source code.
    Unless this is homework, why would you want to know
    this information?That sounds, like you know the answer, but can't tell me, because it's the most important treasure in the world and THEY will kill you if you tell others... :-)
    No, it's not a homework and I don't want any source code from you, I'm a curious guy.

  • Method fprint(String) is undefined for the type JspWriter.

    please help me with this problem
    below is the jsp code written to access the data from the database and to display it in the new page.
    <%@ page
         import = "java.io.*"
         import = "java.lang.*"
         import = "java.sql.*"
    %>
    <%
         Connection dbconn=null;
         ResultSet results;
         PreparedStatement sql=null;     
                   String empid1=request.getParameter("empids");     
              try
    String driver = "com.mysql.jdbc.Driver";
              Class.forName(driver).newInstance();
                   dbconn =DriverManager.getConnection("jdbc:mysql://localhost/hris","root","redhat");
                   int empid11;
                   empid11=Integer.parseInt(empid1);
                   sql = dbconn.prepareStatement("select * from employee where empid=?");
                   sql.setInt(1,empid11);
                   results=sql.executeQuery();
                   results.next();
    out.print("<html>");
    out.print("<head>");
    out.print("</head>");
    out.print("<body>");
    out.print("<table width=810 border=0>");
    out.print("<tr>");
    out.print("<td width=210>");
    out.print("Employee Id");
    out.print("</td>");
    out.print("<td width=584>");
    int emp=results.getInt("empid");
    out.print(emp);
    out.print("</td>");
    out.print("</tr>");
    out.print("<tr>");
    out.print("<td>");
    out.print("FirstName");
    out.print("</td>");
    out.print("<td>");
    String first=results.getString("fname");
    out.print(first);
    out.print("</td>");
    out.fprint("</tr>");
              catch (SQLException s)
                   out.println("SQL Error <br>"+s);
    catch ( Exception x )
                   x.printStackTrace();
    %>
    but when i click the submit button , the error is
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 9 in the jsp file: /HRIS/empsearch1.jsp
    Generated servlet error:
    The method fprint(String) is undefined for the type JspWriter
         org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
         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
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 9 in the jsp file: /HRIS/empsearch1.jsp
    Generated servlet error:
    The method fprint(String) is undefined for the type JspWriter
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:328)
         org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:409)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:297)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:276)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:264)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:563)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:303)
         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)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.15 logs.
    i am not able to rectify the error.

    JavaB wrote:
    Hi ,
    I have a method defined in my dataManagerDAO classIs it dataManagerDAO or DataManagerDAO?
    getNoc( strRppsId) throws Exception {}That's not a legal Java method declaration, so it's clearly not your actual declaration, so I have no idea what your actual declaration is, so I can't tell you what you're doing wrong.
    Now I am calling this method inside my JSP page :
    DataManagerDAO dataMgr = new DataManagerDAO();
    dataMgr.getNoc(strRppsId)..
    But whenver I am running it locally , it fails to compile and gives following error msg :
    The method getNoc(String) is undefined for the type DataManagerDAOQuite obviously you're calling a method getNoc(String) but that method doesn't exist on the DataManagerDAO class. No matter how much you may think you know that it does, you're wrong and the compiler is right.
    Maybe you misspelled or mis-capitalized something. Maybe you're passing the wrong type of argument. Maybe you're still using an older version of the DataManagerDAO class from before you added that method. Not enough information here to say for sure.
    ny clue wats going wrong in here ?I assume you mean "any", not "ny" and "what's", not "wats". Clear, correct, precise communication counts with folks here almost as much as it does with the Java compiler.

  • Error calling native methods

    HI
    I declared a static native method in a class and using the System.loadLibrary() method i load the dll.
    Now if i want to call the method from another class using instance of that class where i declare the native method, it shows an error
    java.lang.SpecifiedPathLink error. I have put the dll outside the package in the same directory.
    can anyone help me regarding this problem

    it shows this exception
    Exception in thread "main" java.lang.UnsatisfiedLinkError: no PerfMonitor in jav
    a.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1491)
    at java.lang.Runtime.loadLibrary0(Runtime.java:788)
    at java.lang.System.loadLibrary(System.java:834)
    at C3.CPUMemoryUsage.<clinit>(CPUMemoryUsage.java:6)
    at C3.Node.main(Node.java:18)

  • Using a string or char as a class when calling a method

    Is there a way to take the string.charAt(int) method and use it as a stand in for a class that is one character long? (Examples below, as I'm sure that question makes no sense out of context.)
    Something like (note the last line):
    import java.util.Scanner;
    public class DRV
         public static void main(String[] args)
              Scanner inpt = new Scanner(System.in);
              String stringy;
              A a = new A();
              System.out.println("Enter 'a': ");
              stringy = inpt.next();
              [stringy.charAt(0)].lineOne();
    }Or will I just have to use a lot of if statements:
    import java.util.Scanner;
    public class DRV
         public static void main(String[] args)
              Scanner inpt = new Scanner(System.in);
              String stringy;
              A a = new A();
              System.out.println("Enter 'a': ");
              stringy = inpt.next();
              if (stringy.charAt(0) == 'a')
                   a.lineOne();
                   System.out.println();
    }I doubt this is possible, but it would be totally awesome if there was something like [stringy.charAt(0)].classmethod();. This would allow me to just use a couple for loops instead of a cluster of if's.
    Thanks for any help.
    Edited by: 797223 on Sep 28, 2010 11:21 PM

    What Kayaman said.
    Another suggestion, slightly more elaborate, is to use class.forName() and reflection to create an instance of the correct class:
    stringy = inpt.next();
    Class clazz = Class.forName(makeClassCase(stringy));
    Object o = clazz.newInstance();
    SomeInterface i = (SomeInterface)o;
    i.lineOne();This assumes that you write a method private String makeClassCase(String s) that returns the correctly cased class name (e.g. transforms 'a' to 'A') and adds the appropriate package name if applicable, and that you define method lineOne() in an interface SomeInterface and in all classes that implement it (assuming I have correctly understood that all your classes do expose the same lineOne() method).
    You'll have to make special provisions for error cases (e.g. the user types a class name that doesn't exist, or that doesn't implement the common interface).

  • 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

  • Calling a method in another JVM instance

    I know you can use RMI to call the methods from classes across the network, but if the class is on the same machine, just in another JVM instance, is there a way to bypass the network layer and have the JVMs communicate directly with each other?

    Its not so much the overhead, as having the
    flexibility, to not have to modify firewall rules
    which disallow loop back traffic and most other non
    http (port 80) traffic if the production server is
    set up that way.You're coding to interfaces anyway, have a factory return either an RMI object which does the actual RMI work, or just a vanilla one if you're just running locally. As far as I know, there isn't a way to entirely circumvent the socket layer with RMI. Anyone know any different?

  • How to call a method if I have a name of a method in String format

    Hi Guys,
    I need an idea how to replace this large code. It has more then 50 else-if in a row
    if ((readerElement.getFunction()).equals("clickButton")) {
    testFrameWork.clickButton();
    }else if ((readerElement.getFunction()).equals("clickButtonWait")) {
    testFrameWork.clickButtonWait();
    }else if ((readerElement.getFunction()).equals("clickCreateJob")) {
    testFrameWork.clickCreateJob();
    Of course switch can't be helpful in my case. I am using a Strings and switch will not make my code better.
    I need something like:
    testFrameWork.((readerElement.getFunction()).toString)() - This is of course bad code but I just want to give an idea what I am looking for
    Can I call somehow method by adding a name of that method by String?!

    While reflections can be error prone, so is maintaining 50 if/else statements or 50 Command classes. You appear to have a good use case.
    Method m = testFrameWork.getClass().getMethod(readerElement.getFunction());
    m.invoke(testFrameWork);

  • How to call a method of a class where the name of method is string

    i have a method of a class in the form of a string and i have the object of the class to which it belongs .what i want to do is call this method.
    for ex:
    S1 s=new S1();
    // this is the object of my class. this class has one method called executeMe()
    String methodname="executeMe";
    //i have the name of the method with me in the form of string.
    so how can i call the class's method in this scenario from the string like what should i write in sucha way that i get s.executeMe(); it is not presumed that this will only be the method that will be called. there maybe some other method too and it has also to be called this way. so please guide.

    S1 s = new S1();
    String name = "executeMe";
    Method m = s.getClass().getDeclaredMethod(name,null); // no parameters
    m.invoke(s,null);Built from memory, maycontain flaws.

  • Call a static method via RFC

    Hello people,
    How can I call a static method via RFC?
    I am in SRM and would like to call a static method defined in ECC.
    What is necessary to be configured in this class/method?
    Thanks!!!

    You may need to write RFC in ECC and call it from SRM
    and write following code in RFC for call a static method
    reference_obj=>method_name
    EXPORTING

  • Converting a string to Class object and calling its method

    I have recently moved to Java and I need help on this specific issue given below.
    I have to do this :
    ValModule1 val1 = new ValModule1();
    ValModule2 val2 = new ValModule2();
    if(val1.checkModule(xmlDocument)){
    $i++;
    There are many ValModule* classes and they all have the method called checkModule in them. I need to instantiate each class and run the checkMethod which returns true or false. My problem is that I am trying to get the name of the module (if it is ValModule1 or 2 or 3) from the user. What I get from the user is the name of the class for which I should call checkModule method on.
    how can I convert this string validationname given by the user and instantiate that class and call the method?
    I have tried this:
    String str="c:/xpathtest/src/Plugin_Config.xml";
    File xmlDocument = new File(str);
    String cls = "ValModule1"; // assuming this is what the user gave me
    Class t = Class.forName("ValModule1");
    Object o = t.newInstance();
    After that if I try
    if(o.checkModule(xmlDocument)){
    $i++;
    It gives me an error saying that it is not an existing method
    cannot resolve symbol
    [javac] symbol : method checkModule (java.io.File)
    [javac] location: class java.lang.Object
    [javac] if(o.checkModule(xmlDocument)){
    [javac] ^
    [javac] 1 error
    Can you please let me know where I am screwing up :-) ? If you need me to put both the programs I can do that too. Thanks in Anticipation

    I have recently moved to Java and I need help on this
    specific issue given below.
    I have to do this :
    ValModule1 val1 = new ValModule1();
    ValModule2 val2 = new ValModule2();
    if(val1.checkModule(xmlDocument)){
    $i++;
    There are many ValModule* classes and they all have
    the method called checkModule in them. I need to
    instantiate each class and run the checkMethod which
    returns true or false. My problem is that I am trying
    to get the name of the module (if it is ValModule1 or
    2 or 3) from the user. What I get from the user is
    the name of the class for which I should call
    checkModule method on.
    how can I convert this string validationname given by
    the user and instantiate that class and call the
    method?
    Define an interface containing the method all your classes have in common, cast the Object reference returned by newInstance to that interface, then you can call that method.
    Good Luck
    Lee

  • Calling methods by strings

    Hi,
    I'd like to know if it is possible to call a method using a string eg:
    String aMethod = "someMethod()";
    is it possible to call the method contained into the aMethod String?
    thanks for your help
    Nicolas piguet

    This too.
    java.reflect.Method
    http://java.sun.com/products/jdk/1.1/docs/api/java.lang.reflect.Method.html

  • String calling a method help!

    public void whichcom(String command)
              if(command == "q"){qmethod();}
              if(command == "l"){lmethod();}
              if(command == "n"){nmethod();}
              if(command == "p"){pmethod();}
              if(command == "d"){dmethod();}
              if(command == "a"){amethod();}
              if(command == "$"){$method();}
              if(command == "?"){questionmethod();}
              else
                   System.out.println("This is not a recognised Editor Command");
    Can anyone tell me why whenever command is one of the characters that calls a method up above the method doesnt run?

    You want to use
    command.equals("q")
    rather than
    command == "q"
    The reason is that "q" is an object reference--to an object of type String, to be exact. The == for references evaluates to true iff both references refer to the same object. However, command and "q" each refer to distinct String objects. String.equals returns true if the contents of the two Strings (that is, the sequence of characters for each) are the same.
    (Note: You might occasionally see the == operator appear to work the way you tried to use it here. That has to do with the fact that sometimes two String constants share the same array of characters. Don't count on this though.)
    See
    http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html#equals(java.lang.Object)

Maybe you are looking for

  • "relative" positioning of buttons in a JFrame

    I want to draw an image as a background on a JFrame and then position several buttons in the frame such that when the frame is resized, the background is resized and the buttons remain "over" the same thing in the background image. I've tried to "do

  • Calm down

    Lots of folks have gotten some serious bunches in their undies here over problems with the Mac App Store, but let's calm down and step back for a minute. Consider... *The Mac App Store is brand new* If something doesn't work just yet, back off, give

  • Bringing in a GB project to a pro studio... questions

    Have a piece that I want professionally mixed and mastered. The engineer at a studio gave me some specific instruction for bringing this project in. Of course they are using protools so I can't just bring in the .band file. Said I need to export all

  • Searching for a more elegant way to write my where clause.

    Hi, I have a table T which has two columns : X(Varchar2(100)), and Y(Varchar2(100)).I want to know all the rows in the table T for which two conditions are simultaneously true: the first condition is X is not null or Y is not null, and the second con

  • Sql date comparision

    hello i am using oracle 8.1.7..i am new to oracle i have a date column in the table, i need to get this date and check whether this date is a sunday or saturday, if they are i need to make this date to next business day (i.e monday-friday), i also ne