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

Similar Messages

  • Converting a String to an Object

    Is there some way of converting a String (from a textfield) to an Object? What I want is something similar to the functionality offerred by a JTable. This is because I want the user to be able to input a value of any type to the textfield (e.g. String, int, boolean, etc) and get its object representation ...
    Would a simple cast do ?
    David

    dattard,
    A string is an object, when someone enters something into a JTextField, REGARDLESS of what it is (int, double, string, etc) it is stored in the string text in that text field (JTextField.getText()).
    So if someone enters in "123", its the STRING 123, not the number one hundred and twenty three... to GET the number 123, you'll need to do something like:
    int value = Integer.parseInt( myTextField.getText() );
    to have the string parsed for the value, if you want a double, same idea:
    double value = Double.parseDouble( myTextField.getText() );
    NOTE: The number wrapper classes (Integer, Double, Float, etc.) contain "parseXXXX" methods that allow you to parse a corresponding numeric value out of a String object.
    Also, when a user enters ANYTHING into a text input field of any type, its ALWAYS a String, if you want a different version of what they entered, its up to you to parse it and decide what it was.

  • Changing an object by calling a method in another class that returns nothin

    How can a method like for example Arrays.sort(Object[] a) work? The method has a return statement void, so how come the array passed into the method "magically" end up as being sorted when we look at it in another class after having called this method?

    jverd wrote:
    sunfun99 wrote:
    Since references really are more like addresses, jverd's adress-on-pieces-of-paper analogy is the best, but certainly not because the addresses on the pieces of paper are copies of the address (they aren't). We may just be splitting ever finer semantic hairs here, but how is it not a copy of the address?It is a finely split hair - and ultimately just a difference of language use, I think.
    We scribble on pieces of paper and thereby have at least two things to deal with: the scribble, and the location. It is unfortunate, but in English both things are referred to as "the address". The scribble has qualities like "red", "legible" etc, the location has qualities like "distant", "next door to the president": so they do seem to be different things.
    We use "address" for both: "I can't read this address" vs "Go to this address". Children make jokes based on the ambiguity: "How do you spell it."
    But then there's a third thing: the denotation of the location by the scribble. (denotation here == reference/pointing-at/leash/stick etc). It really does seem to be a third thing. (With apologies to Jean Buridan) consider a person who has lat/long coordinates explained to them for the first time and is handed a piece of paper with coordinates on it. They are asked "Do you know who lives here?" and they answer "Yes, I know the person at this address!". Most would say the statement is false - even if it turns out they were handed their own address. Their assertion of knowledge is an assertion about the denotation of the location by the coordinates, not about the location itself.
    So what is copied by a scribe or a photocopy machine when it copies an address? Clearly it's the scribble, not the location. The scribble is duplicated, the location is not. But what about the denotation of the location by the scribble? Not withstanding the above example (and especially in contexts where knowledge and similar concepts are not involved), you could say that the denotation of the location by the scribble is a value. In other words you could hold that two denotations of some location are not just equal but identical iff they denote the same location. (You could, but you needn't.) It is in this sense that the pieces of paper bear, not copies of the address, but the same address.
    (Exactly the same applies to "pointers" ie signposts. If you have two "north pole" signs (1) The are different signs (2) They point to the same place (3) They are two signs bearing one and the same reference.)
    Edited by: pbrockway2 on Mar 15, 2009 12:49 PM

  • Re: Beginner needs help using a array of class objects, and quick

    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ? In html, I assume. How did you generate the html code of your three classes ? By help of your IDE ? NetBeans ? References ?
    I already posted my question with six source code classes ... in text mode --> Awful : See "Polymorphism did you say ?"
    Is there a way to discard and replace a post (with html source code) in the Sun forum ?
    Thanks for your help.
    Chavada

    chavada wrote:
    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.You think she's still around almost a year later?
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ?Just use [code] and [/code] around it, or use the CODE button
    [code]
    public class Foo() {
      * This is the bar method
      public void bar() {
        // do stuff
    }[/code]

  • Error while updating data using session and call transaction method

    Hi all,
        i have to update data using MM01 transaction from flat file to database.i have used both session method and call transaction method to do that.in both the methods data has been transferred from internal tables to screens but while updating the data that is by clicking the ok-code at the end of the transaction iam getting a dialogue box stating
       SAP EXPRESS DOCUMENT "UPDATE WAS TERMINATED" RECEIVED FROM AUTHOR "SAP".
      please tell whether the problem lies and solution for that.
                                       thanks and regards.

    hi,
    check your recording.check whether u saved your material no in recording or not.
    once again record the transacton mm01.
           MATNR LIKE RMMG1-MATNR,
           MBRSH LIKE RMMG1-MBRSH,
           MTART LIKE RMMG1-MTART,
           MAKTX LIKE MAKT-MAKTX,
           MEINS LIKE MARA-MEINS,
           MATKL LIKE MARA-MATKL,
           BISMT LIKE MARA-BISMT,
           EXTWG LIKE MARA-EXTWG,
    these are the fields which u have to take in internal table.
    this is the record which i took in my flatfile.use filetype as asc and hasfieldseperator as 'X'.
    SUDHU-6     R     ROH     MATSUDHU     "     001     7890     AA
    i did the same.but i didn't get any error.

  • Log file in session and call transaction methods

    Hi Experts,
    How to see log file in session and call transaction methods?

    hi
    If its a session then goto SM35, select ur session and then u can see log button over there at the top... that will give the log
    If its a call transaction then in ur program u need to declare internal table IT_MSGS like this
    DATA:  IT_MSGS LIKE BDCMSGCOLL OCCURS 0 WITH HEADER LINE.
      LOOP AT IT_SALES.
        PERFORM POPULATE_BDC.
        CALL TRANSACTION 'VA01' USING IT_BDCDATA
                                      MODE MODE
                                      UPDATE UPDATE
                                      MESSAGES INTO IT_MSGS.
        IF NOT IT_MSGS[] IS INITIAL.
          LOOP AT IT_MSGS.
            CALL FUNCTION 'FORMAT_MESSAGE'
              EXPORTING
                ID        = IT_MSGS-MSGID
                LANG      = 'EN'
                NO        = IT_MSGS-MSGNR
                V1        = IT_MSGS-MSGV1
                V2        = IT_MSGS-MSGV2
                V3        = IT_MSGS-MSGV3
                V4        = IT_MSGS-MSGV4
              IMPORTING
                MSG       = V_MSG
              EXCEPTIONS
                NOT_FOUND = 1
                OTHERS    = 2.
            IF SY-SUBRC <> 0.
              MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                      WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
            ENDIF.
            WRITE:/ V_MSG.
          ENDLOOP.
        ENDIF.
      ENDLOOP.
    This will create a log for you, dont forget to award points if found helpful

  • In session and call tansaction methods, which is better . why?

    hi
    in session and call tansaction methods, which is better . why?

    see the link:
    <a href="http://www.itcserver.com/blog/2006/06/30/batch-input-vs-call-transaction/">batch inpunt VS call transaction</a>
    "The most important aspects of the session interface are:
    <b>Asynchronous processing</b>
    Transfer data for multiple transactions
    Synchronous database update. During processing, no transaction is started until the previous transaction has been written to the database.
    A batch input processing log is generated for each session
    Sessions cannot be generated in parallel. The batch input program must not open a session until it has closed the preceding session.
    The most important features of CALL TRANSACTION USING are:
    <b>Synchronous processing</b>
    Transfer of data from an individual transaction each time the statement CALL TRANSACTION USING is called
    You can update the database both synchronously and asynchronously. The program specifies the update type.
    Separate LUW (Logical Units of Work) for the transaction. The system executes a database commit immediately before and after the CALL TRANSACTION USING statement.
    No batch input processing log"
    I hope I have been able to help you.
    cordial greetings.

  • Mappimg and updation in bdc 'session ' and 'call transaction' methods

    What will happen if error record comes while updating in session method and call transaction method.

    Hi,
    If any error comes in Session method U can find that error in SM35->Log
    and updste again database for those enteries
    In cll transaction Method U have to handel error manually . for this u have to use structure BDCMSGCOL and Table T100.
    Regards
    Gaurav

  • Where can i find the theory for session and call transaction method

    hi
    where can i find the theory for session and call transaction method
    bye

    check this link
    http://www.sap-img.com/abap/learning-bdc-programming.htm
    http://www.planetsap.com/bdc_main_page.htm
    lsmw, bapi, bdc- session, bdc-calltransaction
    u can get it in help.sap.com also

  • Difference between Session method and Call transaction method

    Hi,
    Difference between Session method and Call transaction method in BDC

    Hi,
    SESSION method:
    Is a standard procedure for transferring large amount of data into the R/3 system.
    Data consistency is ensured because batch input uses all thje checks conducted on the normal screen.
    It is a two step procedure:
    1.  Progarm: creates batch input session. This session is the data file that includes everything to begin the transaction.
    2. Process session: Which then actually transfers the data to database table.
    In this method an ABAP/4 program reads the external data that is to be entered in the SAP system and stores the data in a session.
    A session stores the actions that are required to enter your data using normal SAP transactions i.e. data is transferred to session which inturn transfers data to database table. Session is an intermediate step between internal table and database table.
    Data along with it's actions are stored in session. i.e. data for screen fields, to which screen it is passed, the program name behind it and how next screen is processed.
    When the program has finished generating the session, u can run the session to execute the SAP transactions in it.
    BDC_OPEN_GROUP
              You create the session through program by BDC_OPEN_GROUP function.
    1) User Name: User Name.
    2) Group       : Name of the session
    3) Lock Date : The date when you want to process the session.
    4) Keep        : This parameter is passed as 'X' when you want to retain session even       after processing it.                    
    BDC_INSERT
         Data is transferred to session by BDC_INSERT.
    BDC_CLOSE_GROUP.
         With this function the session will be closed.
    CALL TRANSACTION method.
    Syntax: call transaction <tr code> using <bdctab>
                                 mode <A/N/E>
                                 update <S/A>
                                 messages into <internal table>.
    <tr code>   : transaction code
    <bdctab>   : Name of the BDC table
    mode: mode in which you execute the transaction.      
    A   : all screen mode ( all the screens of the transaction are displayed )
    N   : no screen mode ( no screen will be displayed when you execute the transaction )
    E   : error screen ( only those screens are displayed where in you have error record )
    Update type:
    S: synchronous update in which if you change data of one table then all the related tables gets updated and SY_SUBRC is returned for once and all.
    A: asynchronous update in which if you change data of one table, the sy-subrc is returned and then updation of other affected tables takes place. So if system fails to update other tables still sy-subrc returned is zero.(that is when first table gets updated ).
    messages: if you update database table, operation is either successful or unsuccessful. These messages are stored in internal table. This internal table structure is like BDCMSGCOLL.
           TCODE:  transaction code.
           DYNAME: batch input module name.
           DYNNUMB: batch input dyn no.
           MSGTYP:  batch input message type.
           MSGSPRA: batch input language id of message.
           MSGID:    message id.
           MSGV1….MSGV5: message variables
    For each entry which is updated in the database table message is available in BDCMSGCOLL.
    Reward if useful
    Regards
    Srinu

  • How can I convert a string to an object or class

    I would like to read a file representing a class, and convert it to an object or a class (object preferred). Other postings suggest using javax.tools.JavaCompiler to convert from a string but then say that this is not always available (posting on 1 Jan 09). If this is still not universally available is there another way to do this? If this is not available, are there any examples of how it should be done?
    My understanding from what I've read is to read the file into a String then compile the String using javax.tools.JavaCompiler, which is an Interface.
    thanks

    skidmarks wrote:
    What i would like to do is to take a Java file representing a class and compile it at runtime. However, the comment about a JDK being available at runtime makes this unattractive.So, you want to compile .java files, but you don't want to have to use a compiler?
    The next guess would to be to create a .jar file and reference it at runtime. Here's the scenario:Eh? How is that even remotely equivalent?
    1. People using the 'system' will have a varied knowledge of Java.
    2. My hope was to require that anyone using the program would only need to create a Java Class file,You mean a Java source file. You have said that YOU want to create the .class file. If they are creating the .class file, then all you need to do is load it with a ClassLoader and start using it.
    You might try clarifying your requirements a bit.
    In either case, the Class Files would look like:
    public class Name {
    int field1;
    float field2;
    } With all the field types being simple Java Primitives.What is the point of this? What are you ultimately trying to accomplish, that can be served by user-defined groups of primitives, with no complex object graphs and no user-defined methods?
    Depending on what you're really getting at, using scripting features via beanshell, groovy, or javascript might be an approach to consider, or using Scala to produce a domain-specific language (although I suspect that last may be overkill, and beyond your current skill level).
    If this is so, is there any way to create a .jar file at runtime? Do I have to exec("jar") or is there another way.A .jar file is just a .zip file with a manifest. Look at the java.util.jar package. But note that creating a .jar file has nothing to do with the rest of what you're asking about.

  • How to convert a string into an objects name?

    Hi
    I have the following problem;
    I have a string
    String a = "e1"
    and a method
    call(Event e1) that calls the "Event" class with object the name of the string a.
    How can I convert the strings name into an object so as to use it in the "call" method?
    Any ideas?
    Thanks in advance

    I don't know if this helps you, but you can do things like this.
    String a = "com.example.SomeEvent";
    //Instantiate com.example.SomeEvent
    Object o = Class.forName(a).newInstance();SomeEvent must have a non-argument constructor for this to work.
    Class that will be instantiated depens on runtime value of String a, and can be different across different executions of the program.

  • How to code a method that returns string for class object

    I have a class named Address.
    public class Addresss{   
    private String street;   
    private String city;            // instance variables  
    private String zipcode;}I have been asked to write a method that returns a string for Address object. I dont understand how to create address object.Can anyone pls help me understand.
    do I have to write (for creating object)
    Address addressObject  = new Address(); ( coding method that returns a string for address object) ---> I really dont understand this part.

    looks almost right. The problem is that your method name AddressBookEntry does not match the name of your class AddressBook and therefore is not a constructor.
    Furthermore, you probably need to make a distinction between a single entry into the address book which consists of a single name and a single address, (which is just what you have done) and an address book itself which is probably a list of AddressBookEntries
    So for your code I would change the class that you called "AddressBook" to "AddressBookEntry" and have a third class that represents the collection of AddressBookEntries.
    Now to be honest, I don't know why you keep the name split apart from the street address portion of the address. I would be more inclined to keep the name as a field of the address itself, but it's your code, you carve it up the way you like.

  • How to store Connection object and call it from other programs.

    Hi,
    I am trying to connect to the database, store the connection object and use this connection object from other standalone java programs.
    Can any one tell me how to do this? I've tried in the following way:
    In the following program I am connecting to the database and saving the connection object in a variable.
    public class GetKT2Connection {
       public static void main(String[] args) {
          String url = "jdbc:odbc:SQLDsn;
          String dbUser = "sa";
          String dbPwd = "sa";
          Connection kt2conn = Connection connection = java.sql.DriverManager.getConnection(url, dbUser, dbPwd);
          if(kt2conn == null) {
             System.out.println("Database Connection Failure!");
          else {
             System.out.println("Connected to Database...");
         GetKTConnectionObj.storeKT2ConnectionObj(kt2conn);
    } Here is the program to save connection object in a variable.
    public class GetKTConnectionObj {
       static Connection kt2Connection = null;
       public static void storeKT2ConnectionObj(Connection conn) {
       kt2Connection = conn;
       public static Connection getKT2ConnectionObj() {
       try {
          return kt2Connection;
       catch(Exception e){
          System.out.println(e);
      return null;
    }Now from the following code I am trying to get the connection object that is stored. But this is throwing NullPointerException.
    public class Metrics_Migration {
      public static void main(String args[]) {
         try {
        java.sql.Connection connection_1 =   GetKTConnectionObj.getKT6ConnectionObj();
         catch(Exception e){
    }

    kt2Connection is null. You need to store it first, to make it not null. Otherwise it will stay null forever. And why on earth are you trying to do this THIS way?
    If you are running the two applications separately, it wont work either.

  • Why is the Integer wrapper class object and primitive object equal ?

    This is my code :
    package obectorientation;
    public class oo3 {
         public static void main(String[] args) {
              int x=1; float y=1.0F;
              int x1=1;
                                    Integer y1= new Integer(1);
              if(x1==y1)
                   System.out.println("Equal");
              else
                   System.out.println("NOT Equal");
    O/P : EqualMy question is why are x1 and y1 equal ? Won't y1 be a different object and x1 just a primitive variable ?
    Thanks in Advance.

    Specifically, it's because y1 gets unboxed before the comparison. What's really happening is effectively: if ( x1 == y1.intValue() )

Maybe you are looking for