Invoking methods extracted from a string?!?

Hi everybody. I hope the subject is not confusing. What I'm really looking for is some Perl-like behaviour in Java. In Perl its possible to execute subroutines (basicly methods) extracted from a string ("&sub()"). Is there anything similar in Java?
What I would like to do is to process a string and if it has a method (object.getTime()), the method will be called and the return value stored in its place.
Please let me know if more explanation is needed.
Thanks in advance for all the help!
Leo.

I use a language called MUMPS where you can do that as well - execute strings as commands etc. I don't know much about Reflection but it looks like you can get method (Objects) from strings and execute them as well ...

Similar Messages

  • How to extract from a string ?

    Hello , I have this string and I need to extract 4 parts (in bold) from the string , my string is :
    '(invoice) dear client : tom cruise you Buy *408* from MENA.CA @ *6.93* 01/10/09 watheeqa'
    What is the best technique to do that?
    Thanks

    Hi,
    oais wrote:
    Hello , I have this string and I need to extract 4 parts (in bold) from the string , my string is :
    '(invoice) dear client : tom cruise you Buy *408* from MENA.CA @ *6.93* 01/10/09 watheeqa'
    What is the best technique to do that?
    ThanksThat depends on how you know the 4 parts are what you showed, and not
    '<b>(invoice) dear client: tom</b> cruise you Buy 408 from MENA.CA @ 6.93 01/10/09 watheeqa'
    or
    '<b>(invoice)</b> dear client: <b>tom cruise</b> you Buy 408 from MENA.CA <b>@</b> 6.93 01/10/09 <b>watheeqa</b>?'
    or
    '(invoice) dear client: <b>tom cruise</b> you Buy 408 from MENA.CA @ 6.93 <b>01/10/09 watheeqa</b>'
    Will there always be exactly four parts you need to pick?

  • Invoking method with reflection - with String[] params

    Hi there,
    I have a method that I need to call with reflection. This method has one parameter
    public void setArgs(String args[])
    I'm trying to invoke it by reflection. I tryied this but didn't work:
    Class[] parameterArgs = {String[].class};
    Method mCallArgs = objClasseChiamata.getClass().getMethod("setArgs",parameterArgs);
    Object[] nomeArgs = new Object[]{"Luca","Alessio"};
    //I try too:
    //String[] nomeArgs = new String[]{"Luca","Alessio"};
    mCallArgs.invoke(objClasseChiamata ,nomeArgs);     
    It compile ok,
    but in Runtime I find this error:
    java.lang.IllegalArgumentException
    java.lang.Throwable()
    java.lang.Exception()
    java.lang.RuntimeException()
    java.lang.IllegalArgumentException()
    java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object [])
    void reflection.TestReflection.main(java.lang.String [])
    Thank you,
    Alessio

    The thing that goes in the Object[] is the paramaters. The parameter is one String[], not two Strings:
    Object[] nomeArgs = { new String[] {"Luca", "Alessio"} };
    mCallArgs.invoke(objClasseChiamata ,nomeArgs);
    // or
    mCallArgs.invoke(objClasseChiamata, new Object[] { new String[] {"Luca", "Alessio"} });Note that there's no reason to use "new Object" when you're initializing a named array reference (just like you initialized the Class[] above).

  • Invoke method dynamically  based on string name.

    In my code i have some 50 odd if else condition:
    if(command.equals("abc"))
    //call abc method
    abc();
    else if(command.equals("xyz"))
    // call xyz();
    and so on........
    now based on command string i need to call a method whose name is identical to command string.
    I have used reflection to do this and it works. But just need to know ,
    is there any other approach available?
    Also, it is better to use reflection or just write 50 if else statements and call each function.
    TIA,
    Sachin

    hey i asked the same question a little while ago and got some
    very good feedback at this thread
    http://forum.java.sun.com/thread.jspa?threadID=646255
    i had written some test code but i cant find it.
    you will be looking for this kind of stuff though
    (this isnt intelligible code)
    Object o = Class.forName("hto");
    Field[] fields = ht.getClass().getDeclaredFields();
    Class class1 = ( fields[1].getType() );
    Class class2 = Class.forName("MyClassName");
    Class[] param = { value.getClass() };
    Object[] invokeParam = { value };
    Class[] prim = { Class.forName("HackThis") };
    Method method = ht.getClass().getMethod("set" + var, param);
    method.invoke(ht, invokeParam);

  • How to extract an integer or a float value from a String of characters

    Hi i have a problem getting to a float value within a string of characters..
    for instance the string is
    "numberItem xxxxxxxxx 700.0" (each x is a space..the forum wouldnt let me put normal spaces for some reason)
    how do i store 700.0 in a float variable
    remember the string is obtained from an inputfile
    so far i got the program to store the inputfile data line by line in a String array..i tried tokenizing the string to get to the the float value but since i have mulitple spaces within my string, the token method only gets "numberItem" from the above String
    This is all i have so far:
    String c;
    String Array[] =new String[g]; (i used a while loop to obtain g(the nubmer of lines in the file))
    while((c=(cr.readLine()))!=null)
    Array[coun]=c;
    it would be reallllllllllllllllllllllllllllllllllllllly easy if there was a predefined method to extract numeric values from a string in java..
    Edited by: badmash on Feb 18, 2009 5:50 PM
    Edited by: badmash on Feb 18, 2009 5:50 PM
    Edited by: badmash on Feb 18, 2009 5:55 PM

    badmash wrote:
    Hi i have a problem getting to a float value within a string of characters..
    for instance the string is
    "numberItem xxxxxxxxx 700.0" (each x is a space..the forum wouldnt let me put normal spaces for some reason)
    with the space included
    how do i store 700.0 in a float variable
    remember the string is obtained from an inputfile
    so far i got the program to store the inputfile data line by line in a String array..i tried tokenizing the string to get to the the float value but since i have mulitple spaces within my string, the token method only gets "numberItem" from the above StringHuh?
    Not true.
    Anyway why not use string split, split on spaces and grab the last element (which by the format you posted would be your 700.0)
    Then there is the Float.parseFloat method.
    It is easy.
    And another thing why not use a List of Strings if you want to store each line? (And why did you post that code which doesn't really have anything to do with your problem?) Also in future please use the code formatting tags when posting code. Select the code you are posting in the message box and click the CODE button.

  • Extract int from a string

    Hi,
    I am curious if there is an easy way to extract an int value from a String.
    For example, "Rb23" to get 23. The length of the part in front of the integer is variable.
    Thanks

    this seems to work:
    public int extract(String s) {
         String result = "";
         char c[] = s.toCharArray();
         int j = c.length-1;
         if (!Character.isDigit(c[j])) {
              return 0;
         do {
              result+=c[j--];
         } while (j > 0 && Character.isDigit(c[j]));
         return Integer.parseInt(new StringBuffer(result).reverse().toString());
    }it will return 0 if no numbers are found at the end of the string

  • Java method call from c passing string more info

    I am trying to call a java method from c passing a String as an argument.
    my C code is as follows.
    //Initalise jstring and class (to recieve String)
    jstring textp;
    jclass texts = (*env)->GetObjectClass(env, obj);
    jmethodID text = (*env)->GetMethodID(env, texts, "texture", "([Ljava/lang/String;)V");
    //Create a new jstring from the char* texturePath (in textures)
    //call the java method with the jstring
    textp = (*env)->NewStringUTF(env,ret.textures->texturePath);
    (*env)->CallVoidMethod(env, obj, text,textp);
    //java code
    // texture which recieves a string
    public void texture(String texturePath){
    The error I get is as follows:
    SIGSEGV 11 segmentation violation
    si_signo [11]: SEGV
    si_errno [0]:
    si_code [1]: SEGV_MAPERR [addr: 0xc]
    stackpointer=FFBED790
    "Screen Updater" (TID:0x4f9060, sys_thread_t:0x4f8f98, state:CW, thread_t: t@11, threadID:0xf2d31d78, stack_bottom:0xf2d32000, stack_size:0x20000) prio=4
    [1] java.lang.Object.wait(Object.java:424)
    [2] sun.awt.ScreenUpdater.nextEntry(ScreenUpdater.java:78)
    [3] sun.awt.ScreenUpdater.run(ScreenUpdater.java:98)
    "AWT-Motif" (TID:0x40be50, sys_thread_t:0x40bd88, state:R, thread_t: t@10, threadID:0xf2d71d78, stack_bottom:0xf2d72000, stack_size:0x20000) prio=5
    [1] sun.awt.motif.MToolkit.run(Native Method)
    [2] java.lang.Thread.run(Thread.java:479)
    "SunToolkit.PostEventQueue-0" (TID:0x431950, sys_thread_t:0x431888, state:CW, thread_t: t@9, threadID:0xf2e71d78, stack_bottom:0xf2e72000, stack_size:0x20000) prio=5
    [1] java.lang.Object.wait(Object.java:424)
    [2] sun.awt.PostEventQueue.run(SunToolkit.java:407)
    "AWT-EventQueue-0" (TID:0x430ea8, sys_thread_t:0x430de0, state:CW, thread_t: t@8, threadID:0xf3071d78, stack_bottom:0xf3072000, stack_size:0x20000) prio=6
    [1] java.lang.Object.wait(Object.java:424)
    [2] java.awt.EventQueue.getNextEvent(EventQueue.java:212)
    [3] java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:100)
    [4] java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:91)
    [5] java.awt.EventDispatchThread.run(EventDispatchThread.java:83)
    Exiting Thread (sys_thread_t:0xff343db0) : no stack
    "Finalizer" (TID:0x154e98, sys_thread_t:0x154dd0, state:CW, thread_t: t@6, threadID:0xfe391d78, stack_bottom:0xfe392000, stack_size:0x20000) prio=8
    [1] java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:146)
    [2] java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:168)
    [3] java.lang.ref.Finalizer$FinalizerWorker$FinalizerThread.run(Finalizer.java:124)
    "Reference Handler" (TID:0x1506a0, sys_thread_t:0x1505d8, state:CW, thread_t: t@5, threadID:0xfe3c1d78, stack_bottom:0xfe3c2000, stack_size:0x20000) prio=10
    [1] java.lang.Object.wait(Object.java:424)
    [2] java.lang.ref.Reference$ReferenceHandler.run(Reference.java:130)
    "Signal dispatcher" (TID:0x13d180, sys_thread_t:0x13d0b8, state:MW, thread_t: t@4, threadID:0xfe3f1d78, stack_bottom:0xfe3f2000, stack_size:0x20000) prio=10
    "main" (TID:0x38918, sys_thread_t:0x38850, state:R, thread_t: t@1, threadID:0x25228, stack_bottom:0xffbf0000, stack_size:0x800000) prio=5 *current thread*
    [1] loader.Callbacks.nativeMethod(Native Method)
    [2] loader.Callbacks.main(Callbacks.java:184)
    [3] graphics.GR_MakeTrack.init(GR_MakeTrack.java:60)
    [4] graphics.GR_MakeTrack.main2(GR_MakeTrack.java:49)
    [5] graphics.GR_MakeTrack.main(GR_MakeTrack.java:41)
    [6] control.GE_main.GE_main1(GE_main.java:87)
    [7] control.GE_main.main(GE_main.java:66)
    gmake: *** [run] Abort (core dumped)

    I am trying to call a java method from c passing a
    String as an argument.
    my C code is as follows.
    //Initalise jstring and class (to recieve String)
    jstring textp;
    jclass texts = (*env)->GetObjectClass(env, obj);
    jmethodID text = (*env)->GetMethodID(env, texts,
    "texture", "([Ljava/lang/String;)V");
    Hi Pete,
    your problem is that the method texture you are trying to find does not exist. If you look carefully at your declaration of the method signature in the GetMethodID call you will see "([Ljava/lang/String;)V" which is trying to find a method that accepts a String array as its parameter. Remove the [ from the method signature and it should work ok. You might want to test text (jmethodID) for NULL or 0 before trying to call it as well.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • In the NI Library VI: Extract Numbers, the string control is automatically loaded each time the VI is opened with "Counting to five: one 2 three 4.0 five. Where is this string data coming from?

    Even after deleting the string "Counting to five: one 2 three 4. five." from the string control and replacing it with another string the original string returns after the VI is saved then reopened. Where is this string data coming from? I've attached a copy of the library function. I've been able in my application to get around the problem by replacing the string control with a string constant. But I'm still curious as to what's going on.
    Thanks,
    Chuck
    Solved!
    Go to Solution.
    Attachments:
    Extract Numbers Test.vi ‏9 KB

    Chuck,
    String control has been set to default with the string you are seeing.  To change this, enter the new string, right click the control and select
    Data Operations>>Make Current Value Default
    Now save your vi.

  • Invoking methods in C++ from Java

    I'm invoking the Java Virtual Machine from my C++ program like is described here: http://java.sun.com/docs/books/tutorial/native1.1/invoking/invo.html
    So, I run my C++ program (let's call it C), C invokes the JVM and starts a Java program (let's call it J). C can now invoke methods in J. Now I want J to invoke a method in C. Is this possible?

    Yes it is.
    However your C code that you want to invoke from java must be defined as "native" - that is, it is defined as the implementation for java methods that are declared native.
    The possibly most confusing part is where to put the C code and how to make the java-C linkage.
    o You can put the C code in a DLL, and use a "loadLibrary" call to make it available.
    o Alternatively, and perhaps more likely, your original C/C++program can make "registerNative" calls to the JVM to identify to it the native implementations.

  • Invoke a method by getting method name from properties object

    HI ,
    I am storing method names in a properties file . Can any one tell me , how can I invoke those methods ?? Please Urgent.
    Here is the sample program what I am trying to do . Please tell me how to invoke method which is represented by the String "methodTobeInvoked" in the below program.
    public class HelloWorld {
         private String name="meena";
         public String getName() {
              return name;
         public void setName(String name) {
              this.name = name;
         public static void main(String[] args) {
              try {
                   Properties props=new Properties();
                   props.setProperty("method", "getName()");
              String methodTobeInvoked= props.getProperty("method");
              }catch (Exception ioe) {
                   System.err.println(ioe.getMessage());
    Thanks!!!

    meenaalenoor wrote:
    I am storing method names in a properties file . Can any one tell me , how can I invoke those methods?
    Here is the sample program what I am trying to do.
    Please tell me how to invoke method which is represented by the String "methodTobeInvoked" in the below program.
    public class HelloWorld {
         private String name="meena";
         public String getName() {
              return name;
         public void setName(String name) {
              this.name = name;
         public static void main(String[] args) {
              try {
                   Properties props=new Properties();
                   props.setProperty("method", "getName()");
              String methodTobeInvoked= props.getProperty("method");
              }catch (Exception ioe) {
                   System.err.println(ioe.getMessage());
    }Have you looked at [java.lang.reflect|http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/package-summary.html] ?

  • Extracting the partial string from the string in oracle

    Hello Friends,
    I have a string like this
    var str = '/G/CNH/CNHCornerstone/currentCode/data/Working/Images/ModelImages/png/7402203E-607D-E111-9CA5-005056875BD6.png'
    I want to extract only 7402203E-607D-E111-9CA5-005056875BD6 from the string .
    Please let me know how to implement this ..
    thanks/kumar
    Edited by: kumar73 on Apr 10, 2012 12:34 PM

    hope this works
    set serveroutput on
    declare
      str1 varchar(4000);
      str2 varchar(4000);
    begin
      str1 := '/G/CNH/CNHCornerstone/currentCode/data/Working/Images/ModelImages/png/7402203E-607D-E111-9CA5-005056875BD6.png';
      dbms_output.put_line('string 1 : ' || str1);
      str2 := substr(str1,71);
      dbms_output.put_line('string 2 : '||str2);
    end;
    output
    string 1 : /G/CNH/CNHCornerstone/currentCode/data/Working/Images/ModelImages/png/7402203E-607D-E111-9CA5-005056875BD6.png
    string 2 : 7402203E-607D-E111-9CA5-005056875BD6.png
    PL/SQL procedure successfully completed

  • Data extraction from string

    I'm trying to search a particular value in a string file. The string contains many parameters followed by their values and units. I want to identify and extract, as a number, the value of a particular parameter. The program will basically ask the user to type in (or select from a list of given) parameters in a dialogue box. Then it should display the value of the parameter.
    The string I'm trying to work with, is of the form:-
    SensorOneInMM,34585
    BatteryVoltageInmV,19761
    BattTemp1InC,20
    CliffDistanceLeftInMM,60
    CliffDistanceRightInMM,60
    RightSensor,0
    LeftSensor,0
    CurrentInmAforMotor, 789
    TestingCurrentInmA, 123
    Temp1InC,28
    Temp2InC,28
    BaseCurrentInmA,1342
    ChargeInmV,218
    CurrentInmA,9999
    NotConnected3,0
    Now, for example the value I want to read is the one in Blue color. But the expression, "CurrentInmA" appears several times, in the string. How can I identify the value of the parameter in Blue color??
    Thanks for helping out an amateur!!!
    Cheers.

    Rajat
    I think  you want to extract the value from specific string..
    you can get number of post releted to your question...few are follow
    Post 1
    Post2
    also see attached vi which specific to your problem..
    Attachments:
    Extract frm string.png ‏21 KB

  • Extracting data from a string of characters

    Hi,
    I have a problem that I am having difficulty solving, if anyone has any bright ideas it would be a great help.
    I have a description field in one of my tables and the description would read something like
    my website can be found at www.mywebsite.com, and it is great
    I want to be able to extract the web address from this sentance, so the result would be
    www.mywebsite.com
    I can do this specific for one sentance but I can't find a way to do it for many different sentances.
    cheers in advance

    If you're using 10g, you probably want to do something with regular expressions:
    SQL> with strings as (
      2    select
      3              'my website can be found at www.mywebsite.com, and it is great' str
      4    from
      5              dual
      6    union all
      7    select
      8              'my website can be found at WWW.myWebSite.com, and it is great'
      9    from
    10              dual
    11    union all
    12    select
    13              'our web address is www.mywebsite.co.uk' str
    14    from
    15              dual
    16    union all
    17    select
    18              'http://www.mywebsite.com/great'
    19    from
    20              dual)
    21  select
    22            s.str
    23          , regexp_substr(s.str, 'www\.[a-z0-9-\.?]*', 1, 1, 'i')  extr
    24  from
    25            strings s
    26  /
    STR                                                           EXTR
    my website can be found at www.mywebsite.com, and it is great www.mywebsite.com
    my website can be found at WWW.myWebSite.com, and it is great WWW.myWebSite.com
    our web address is www.mywebsite.co.uk                        www.mywebsite.co.uk
    http://www.mywebsite.com/great                                www.mywebsite.comYou'd be better asking this kind of thing on the PL/SQL (and definitely better asking someone other than me anything further about regular expressions!)

  • Extracting method names from JNI probes

    Hello.
    I would like to use the Call* probes from the hotspot_jni provider. These probes provide as argument a "method id". My question is how I can extract, for instance, the method name from this ID. I saw that JNI provides a method "GetMethodName" but being a dtrace novice, I am unsure how to obtain a handle to the JNI api from within dtrace.
    Any hint would be greatly appreciated.
    Best wishes,
    Eric

    Actually, it can be done. Otherwise, how do you think debugger shows variables and formal parameters?
    You should compile your aplication with debuginng information (for details see tools doc). Then you have 3 options:
    1) run application under debugger and use JVMDI to get everything you want;
    2) use bytecode libraries (BCEL, CGLib etc) to read class file and fetch required information through their API
    3) write your own class file parser based on class file format described in Java Virtual Machine Specification
    First way is quite complex and is definitely not for "production use".
    Second way is the best in case you have time limitations, but size of your application will be increased because of thrid-party libraries.
    Thrid way is the best if you have application size restrictions and have enough time to write simple class file parser to fetch that specific information (1-2 days depending on your experience).
    Have fun ;)

  • Extract words from a string

    select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    PL/SQL Release 11.1.0.7.0 - Production
    CORE    11.1.0.7.0    Production
    TNS for Linux: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - ProductionI want to extract xyz_xyz,abc_abc words from the string ' select * from TEMP_TABLE where trunc(xyz_xyz) = ''xyz'' and trunc(abc_abc) = ''abc'') '
    i have tried with this query...
    select regexp_substr('select * from TEMP_TABLE where trunc(xyz_xyz) = ''xyz'' and trunc(abc_abc) = ''abc'')', 'trunc[^'''']+''') from dual
    can some one help me on this?
    Thanks,
    Mike

    Hi, Mike,
    Mike wrote:
    I apologize for this..
    create table TEMP_TABLE ( col1 varchar2(10),col2 varchar2(10));
    insert into TEMP_TABLE values('   xyz   ','abc      ');
    insert into TEMP_TABLE values('   xyzxyz ','abcabc    ');
    insert into TEMP_TABLE values('   xyz123 ','abc546  ');
    insert into TEMP_TABLE values('xyz','abc');
    commit
    select * from TEMP_TABLE where trim(col1) ='xyz' and trim(col2) ='abc'
    desired output
    col1,col2
    So the correct output is one row, containing these 9 characters
    col1,col2which do not appear in the table. is that right?
    How is that output related to the data that is in the table? Do you want that output to appear if there are any rows where TRIM (col1) = 'xyz' and TRIM (col2) = 'abc' (for example, either of these two rows from you sample data:
    insert into TEMP_TABLE values('   xyz   ','abc      ');
    insert into TEMP_TABLE values('xyz','abc');), and would you want the result set to contain no rows if the table contained no row like that?
    If so,
    SELECT DISTINCT
         'col1,col2'     AS desired_output
    FROM     temp_table
    WHERE     TRIM (col1)     = 'xyz'
    AND     TRIM (col2)     = 'abc'
    ;I hope this answers your question.
    I have a feeling that it doesn't, or perhaps you have more than one question, since this your earlier messages seemed to have something to do with locating text that was surrounded by single-quotes, and the sample data you posted doesn't contain any single-quotes.

Maybe you are looking for

  • One library; multiple Apple IDs (used to purchase)

    I am sure this has been answered in the forums, but I have looked and looked and can't seem to find a definitive answer, so I thought I would ask. To simplify (as it's a little more complex than this, but for this question, it doesn't matter), we hav

  • Oracle 10g with Sun AS 7

    Hello I am trying to use a Oracle DB with a Sun Application server 7, i create a connection pool with the following attributes: serverName: 147.2.9x.xx portNumber: 1521 networkProtocol: thin user: SYSTEM password: xxx databaseName: orcl whn i use a J

  • Delimit end date for pay scale salary ranges (T510N)

    Hi, Some of the pay scale salary ranges (T510N) which we use are no longer valid and I want to delimit the end dates. Has anyone done this before ? Appreciate if you can share the solution. Thanks, Rajesh

  • Strange date output

    Greetings, I have created a CustomTag in Coldfusion that calls a simple class file I created, I'm not sure the output is correct though, Calling template <html> <head><title>test cfx</title></head> <body> <CFX_SimpleMessage NAME="DoodleHead"> </body>

  • TS4471 Aperture (new) crashes on startup

    hi Folks, just purhased Aperture from the App Store for my MacBook Pro (4 year old, dual core, 4 gig ram, OSX 10.7.5) I followed a support FAQ's instructions and trashed the installation, re-installed from the app store. Same thing again, it crashes,