How to instantiate an object from another's class?

Hi... first post here
I have the following problem:
I have a first object, lets call it obj1, of class X (where X could be, for example, 'Class1' or in another moment 'Class2', etc.)
Now, I have another object, obj2, which I wish to instantiate it with the same class as obj1. The problem is I don't always know which class does obj1 belongs, so programming with an if-else statement and the getClass().getName() method is not a solution, since I cannot program for all the possible cases.
I know that with obj1.getClass() I get obj1's class and that with obj1.getClass().getName() I get a String with obj1's class name.
I guess that making obj2 of class Object I can get it, but my question is:
How do I do to create the instance of obj2 so its class in that moment is the same as the class of obj1? (And by the way, how can I use a specific constructor of obj1 for obj2?)
I repeat that the if-else method won't do since the class for obj1 won't always be in a known set of classes.
Thanks for any help or tip you can give me
Javier
from Mexico

You would use the Class.forName() static method to get a Class object of the class you are looking for. Then you would use its newInstance() to create an instance of that class using a no-arguments constructor. If you need some other constructor (and how would you know that?) then Class has a getConstructor(...) method and a getConstructors() method that return one or more Constructor objects you could use. Follow the API documentation from there.

Similar Messages

  • .How to instantiate the innerclass from another class with coded eg.

    How to instantiate the innerclass from another class(both for static & non static) please give me an eg with coding.

    It's just a preference, but I like writing factory methods:
    public class Outer {
        public class Inner {}
        public static class StaticInner {}
        public Inner innerInstance() {
            return new Inner();
        public static StaticInner staticInnerInstance() {
            return new StaticInner();
        public static void main(String[] args) {
            Outer.StaticInner si = Outer.staticInnerInstance();
            Outer outer = new Outer();
            Outer.Inner i = outer.innerInstance();
    }Often, for me, the inner class implements an interface, and the factory method
    lets you hide the implementation class:
    public class Outer {
        private class Inner implements Runnable {
            public void run() {}
        public Runnable runnerInstance() {
            return new Inner();
        public static void main(String[] args) {
            Outer outer = new Outer();
            Runnable r = outer.runnerInstance();
    }

  • How to instantiate an object in a JSP page???

    I want from a JSP page instantiate an object from a client class, for example, and call its methods; one of these methods return me a RecordSet.
    But I don't having success on it. What am I doing wrong??? What would I do??? Have anybody a code sample????
    Regards.

    Hi,
    There's the code that I'm using, they are divided in 3 parts, and I really don't know what is causing this error.
    ********** CLASS conn ******************
    * IT'S THE CLASS THAT DO THE CONNECTION
    * AND EXECUTE THE SQL QUERIES
    import java.sql.*;
    import java.io.*;
    public class conn {
      public static Connection conn;
      public static Statement stmt;
      public static void openConn() throws SQLException {
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        conn = DriverManager.getConnection("jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.24.8)(PORT = 1521)))(CONNECT_DATA =(SERVICE_NAME = ora_aula)))", "grupo6", "grupo6");
        stmt = conn.createStatement();
      public boolean getConectionState() throws SQLException {
        if (conn.isClosed())
          return false;  
        else
          return true;
      public static void closeConn() throws SQLException {
        stmt.close();
        conn.close();
      public static void postSql(String command) throws SQLException {
        stmt.executeQuery(command);
        stmt.executeQuery("COMMIT");
      public ResultSet returnSql(String command) throws SQLException {
        return stmt.executeQuery(command);
    ********** CLASS materia ***************
    * IT'S THE CLASS THAT INSTANTIATE THE
    * conn CLASS AND PASS TO IT THE SQL
    * THAT WILL BE EXECUTED AND RETURN THE
    * RECORDSET
    import java.sql.*;
    public class materia{
       public Integer materia_code;
       public String  materia_description;
       private conn myConn = new conn();
       private ResultSet materia_data;  
       ResultSet showData(comandosql){
         try {
           myConn.openConn();
           ResultSet data = myConn.retornaSql(sql);
           myConn.closeConn();
           return data;
         catch (SQLException sqlexc) {
           System.out.print(sqlexc);
           return null;
    ********** jsp PAGE******************
    * IT'S THE PAGE THAT INSTANTIATE THE
    * materia CLASS AND EXECUTE THE
    * STATEMENT, AND WHERE THE ERROR
    * IS OCURRING
    <%@ page import="java.sql.*" %>
    <%@ page import="materia" %>
    <HTML>
    <TITLE> Products</TITLE>
    <%
        out.println("<B> TEST </B>");
        ResultSet rs;
        materia mat = new materia();
       rs = mat.showData("SELECT * FROM PRODUCTS");
    // THE ERROR OCURR IN THE STATEMENT ABOVE
    // WHAT AM I DOING OF WRONG????
    // ... REST OF CODE
    %> 
    </HTML>Thanks for your help.
    Regards.
    Clayton

  • How to move the objects from Infoarea to another?

    Hi,
    How to move the objects from Infoarea to another?
    Thanx in advance,
    Ravi.

    Hi ..
    If the drag & drop functionality is enabled you can drag the catalog and drop it in another InfoArea just as you do with files on your PC.
    The other procedure is Use the right mouse button to create an InfoObject catalog in the InfoArea. If you want to make a copy of an existing InfoObject catalog, specify a reference InfoObject catalog.
    and check this  thread
    Re: Info Object Mapping to Info Area

  • How to move database objects from one user to another user

    Could someone help how to move database objects from one user to another user
    Thanks in advance

    Thanks a lot for the reply.
    Actually I wanted to know whether there is any command to change the owner ship of the table.
    For ex table1 belongs to user1. can the owner of table1 to be changed to owner2.
    directly using an oracle command. I knew that it can be done using import and export, since the table was 200 million thought the rename command would be faster instead of import and export.
    Thanks Billy for letting me know that it is not possible using oracle query.

  • How to transport CU02 objects from one system to another?

    Hi,
    How to transport CU02 objects from one system (Development) to another (Quality)?

    You need to set up the object dependency IDOC in the partner profile.Message type is KNOMAS. The transaction to send is CLD2.

  • How to send an object from one application to another?

    Hi all,
    I have two applications over the same server. The first application needs to send an object to the other application.
    I try to put the object as a session attribute, but in the moment that the second application tries to get the attribute, the attribute doesn't exist.
    Does anybody now how can pass an object from the one application to the other?

    You can also use JMS

  • How to refer one view from another view?

    Hi,
    I have 2 views in my Adobe Flash Builder mobile app. I need to refer the first view in my second view.
    How to refer one view from another view? Or how to create a reference to a view wherever needed?

    I don't need any data from my first view. In a certain flow, I need to make my first view to be invisible.
    for eg., My First view is in portrait mode. I change the device to Landscape. In the landscape mode, I want to show a completely different view (second view).
    In this case, what happens is, I see my first view in Landscape mode for a second. Then the second view appears. When I change to Landscape mode, only the second view should be seen. I need to make my first view to be completely invisible in the OnOrientationChanging event of
    StageOrientationEvent
    As stage object and StageOrientationEvent works at application level, I need to know how to refer my first view object in the application level.
    private function onOrientationChanging(soe:StageOrientationEvent):void
          MyFirstView.Visible = False; ====> don't know how to refer MyFirstView here
    Is my question clear now?

  • How to call a Java class from another java class ??

    Hi ..... can somebody plz tell me
    How to call a Java Class from another Java Class assuming both in the same Package??
    I want to call the entire Java Class  (not any specific method only........I want all the functionalities of that class)
    Please provide me some slotuions!!
    Waiting for some fast replies!!
    Regards
    Smita Mohanty

    Hi Smita,
    you just need to create an object of that class,thats it. Then you will be able to execute each and every method.
    e.g.
    you have developed A.java and B.java, both are in same package.
    in implementaion of B.java
    class B
                A obj = new A();
                 //to access A's methods
                 A.method();
                // to access A's variable
                //either
               A.variable= value.
               //or
               A.setvariable() or A.getvariable()

  • How do I move objects from other package to a newly created one?

    How do I move objects from other package to a newly created one?
    Thanks!

    Dear Anthony Pham ,
    for changing objects from one package to another package
    open that object for example Report
    open the report and than click GOTO select OBJECT DIRECTIORY ENTRY
    than it will open a popup in that popup click the change and give the new package
    Thanks
    Surendra

  • How can i import contacts from another AIM account to this new one

    If you reference my last ichat question, you will see that I have had serious problems and had to create a new account.
    How can I import contacts from another AIM account to this new one??

    Hi,
    Use AIM for Mac and use the Export and Import features.
    Other than that it is a question on making sure every Single Buddy has more than just their Screen name in the IChat Address Card so it is added to the Address Book and dragging them back from there
    9:08 PM Thursday; February 7, 2008

  • Hi,how can i transport objects from one server to other like (Dev To Qty)

    Hi Sir/madam,
       Can u explain how can i transport objects from one server to other like (Development To Quality To Production).
    Regards,
    Vishali.

    Hi Vishali,
    Step 1: Collect all Transports(with Packages) in Transports Tab(RSA1)- CTO
    Step 2: Release the subrequests first and then the main request by pressing Truck button
    Step 3: STMS or Customized transactions
    Object Collection In Transports:
    The respective Transports should have the following objects:
    1. Base Objects -
    a. Info Area
    b. Info object catalogs
    c. Info Objects
    2. Info Providers u2013
    a. Info Cubes
    b. Multi Providers
    c. Info Sets
    d. Data Store Objects
    e. Info Cube Aggregates
    3. Transfer Rules u2013
    a. Application Components
    b. Communication Structure
    c. Data Source replica
    d. Info Packages
    e. Transfer Rules
    f. Transformations
    g. Info Source Transaction data
    h. Transfer Structure
    i. Data sources (Active version)
    j. Routines & BW Formulas used in the Transfer routines
    k. Extract Structures
    l. (Note) If the transfer structures and related objects are being transferred without preceding
    Base Objects transport (e.g. while fixing an error) it is safer to transport the related Info
    Objects as well.
    4. Update Rules u2013
    a. Update rules
    b. Routines and formulas used in Update rules
    c. DTPs
    5. Process Chains u2013
    a. Process Chains
    b. Process Chain Starter
    c. Process Variants
    d. Event u2013 Administration Chains
    6. Report Objects u2013
    a. Reports
    b. Report Objects
    c. Web Templates
    Regards,
    Suman

  • How to access icloud account from another iphone

    My iphone fell in the water. I am on vacation and need to access info from my calendar. How can i do it from another iphone device?

    Just enter your account details under:
    Settings > Mail, Contacts, Calendar
    and add your account.
    Finished.

  • How can i get data from another database SQL Server use database link from

    I have a database link from Oracle connect to SQL Server database with user cdit connect default database NorthWind.How can I get data from another database(this database in this SQL Server use this database link)?

    hi,
    u should see following documentation:
    Oracle9i Heterogeneous Connectivity Administrator's Guide
    Release 1 (9.0.1)
    Part Number A88789_01
    in it u just go to chapter no. 4 (using the gateway),,u'll find ur answer there.
    regards
    umar

  • How can i transfer songs from another itunes other than mine

    how can i transfer songs from another itunes other than mine

    Purchases made under 1 Apple ID are permanently associated with that Apple ID and CANNOT be transferred to another Apple ID.  So if you want to keep those songs, you'll need to always have access to your dad's account.
    B-rock

Maybe you are looking for

  • How to create an anonymous Distribution List ?

    Hi, I have a growing distribution address list created in the Address Book. When I send that address list from Mail, all the names appear individually and everybody can see everybody's else email. How to make it look like it comes just from me, or my

  • LT29i/ GX - Camera not responding/ 'error' camera not available.

    Hello there. My Xperia's camera has stopped working all of a sudden, i think after an update. I cannot explain how frustrating this is, since ive tried many things to fix it.I have tried restoring my phone. Deleteing everything and starting again. I

  • Mail 7.0 downloads mail from IMAP server

    After upgrading to OS X 10.9, Mail upgraded to 7.0, and downloaded all mail messages (almost 7 GB) from all my IMAP servers. The problem is that I don't want Mail to do that as I don't want to clutter my disk space. I made an archive folder on one of

  • Firmware upgrade to 7.6 causes audio jumps

    I've just updated my two Airport express boxes to firmware 7.6. Now every few seconds there is a jump or glitch playing audio that sounds like a buffer overflowing causing data loss. I've tried unplugging & restarting them both without success. One i

  • Compressing file for web

    Hey, can anyone please advise me about the best way/program settings ect to use when compressing a file for the web. Specifically for preview and download purposes on sites like youtube and facebook. Thanx Stephan