Creating an array of objects of a class known ONLY at RUNTIME

I have a method in a class which expects an array of objects of particular type (say A) as its only argument. I 'invoke' this method using reflection. I have the instances of the class A stored in a Vector. When I do 'toArray' on this vector, what I get back is an array of Objects and not an array of objects of A. I assign this array to the zeroth element of another Object array and pass that array as a second argument to the 'invoke' method. Of course, it throws an Exception saying - argument types mismatch. Because I am sending an array of Objects to a method expecting an array of objects of A. My problem is I don't know A until runtime. So I have to handle whatever I am getting back after doing 'toArray' on a vector as a Generic Object. I know there's another version of 'toArray' in the Vector class. But it's API documentation didn't help a lot.
Can anybody please help me solve this problem? Any sort of hints/code snippet would be of great help.
Does the above description makes any sense? If not, please let me know. I would try to illustrate it with a code sample.
Thanks a lot in advance.

Sorry, for the small typo. It is -
clazz[] arr = (clazz [])java.lang.reflect.Array.newInstance(clazz, n);
instead
Thanks for the reply. I could do this. But I am
getting a handle to the method to be 'invoke'd by
looking at the types of the parameters its
expecting(getParameterTypes). So I can't change it to
accept an array of Generic Objects.
I looked at the java.lang.reflect.Array class to do
this. This is what I am trying to do-
String variableName is an input coming into my
program.
n is the size of the array I'm trying to create.
Class clazz = Class.forName(variableName);
clazz[] arr = (clazz
[])java.lang.reflect.newInstance(clazz, n);
According to Reflection API, it should work, right?
But compiler yells at me saying 'class clazz not
found'.
Any suggestions/hints/help?
Thanks, again.

Similar Messages

  • How to cast an object to a class known only at runtime

    I have a HashMap with key as a class name and value as the instance of that class. When I do a 'get' on it with the class name as the key, what I get back is a generic java.lang.Object. I want to cast this generic object to the class to which it belongs. But I don't know the class at compile time. It would be available only at runtime. And I need to invoke methods on the instance of this specifc class.
    I'm not aware of the ways to do it. Could anybody suggest/guide me how to do it? I would really appreciate.
    Thanks a lot in advance.

    Thanks all for the prompt replies. I am using
    reflection and so a generic object is fine, I guess.
    But a general question (curiosity) specific to your
    comment - extraordinarily generic...
    I understand there's definitely some overhead of
    reflection. So is it advisable to go for interface
    instead of reflection?
    Thanks.Arguments for interfaces rather than reflection...
    Major benefit at run-time:
    Invoking a method using reflection takes more than 20 times as long without using a JIT compiler (using the -Xint option of Java 1.3.0 on WinNT)... Unable to tell with the JIT compiler, since the method used for testing was simple enough to inline - which resulted in an unrealistic 100x speed difference.
    The above tests do not include the overhead of exception handling, nor for locating the method to be executed - ie, in both the simple method invocation and reflective method invocations, the exact method was known at compile time and so there is no "locative" logic in these timings.
    Major benefit at compile-time:
    Compile-time type safety! If you are looking for a method doSomething, and you typo it to doSoemthing, if you are using direct method invocation this will be identified at compile time. If you are using reflection, it will compile successfully and throw a MethodNotFoundException at run time.
    Similarly, direct method invocation offers compile-time checking of arguments, result types and expected exceptions, which all need to be dealt with at runtime if using reflection.
    Personal and professional recommendation:
    If there is any common theme to the objects you're storing in your hashtable, wrap that into an interface that defines a clear way to access expected functionality. This leaves implementations of the interface (The objects you will store in the hashtable) to map the interface methods to the required functionality implementation, in whatever manner they deem appropriate (Hopefully efficiently :-)
    If this is feasible, you will find it will produce a result that performs better and is more maintainable. If the interface is designed well, it should also be just as extensible as if you used reflection.

  • Creating an arrays of objects from a class

    I was wondering does any one know how to create an array of objects from a class?
    I am trying to create an array of objects of a class.
    class name ---> Class objectArray[100] = new Class;
    I cant seem to make a single class but i need to figure out how to create an array of objects.
    I can make a normal class with Class object = new Class

    There are four lines of code in your for-loop that actually do something:
    for(index = 0; index < rooms.length; index++) {
    /*1*/  assignWidth.setWidth(Double.parseDouble(in.readLine()));
    /*2*/  rooms[index] = assignWidth;
    /*3*/  assignLength.setWidth(Double.parseDouble(in.readLine());
    /*4*/  rooms[index] = assignLength;
    }1.) Sets the width of an object, that has been instantiated outside the loop.
    2.) assigns that object to the current position in the array
    3.) Sets the width of a second object that has been instantiated outside the loop
    4.) assigns that other object to the current position in the array
    btw.: I bet you meant "assignLength.setLength(Double.parseDouble(in.readLine());" in line 3 ;)
    Since each position in an array can only hold one value, the first assignment (line 2) is overwritten by the second assignment (line 4)
    When I said "construct a new room-object and assign it to rooms[index]" I meant something like this:
    for(index = 0; index < rooms.length; index++) {
        Room aNewRoom = new Room();
        aNewRoom.setWidth(Double.parseDouble(in.readLine()));
        aNewRoom.setLength(Double.parseDouble(in.readLine());
        rooms[index] = aNewRoom;
    }1.) Constructs a new Object in every iteration of the for-loop. (btw: I don't know what kind of objects you're using, so this needs most likely modification!!)
    2.) set the width of the newly created object
    3.) set the length of the newly created object
    4.) assign the newly created object to the current position in the array
    -T-
    btw. this would do the same:
    for(index = 0; index < rooms.length; index++) {
        rooms[index] = new Room();
        rooms[index].setWidth(Double.parseDouble(in.readLine()));
        rooms[index].setLength(Double.parseDouble(in.readLine());
    }but be sure you understand it. Your teacher most likely wants you to explain it ;)

  • Formatted .data file, reading in and creating an array of objects from data

    Hi there, I have written a text file with the following format;
    List of random personal data: length 100
    1 : Atg : Age 27 : Income 70000
    2 : Dho : Age 57 : Income 110000
    3 : Lid : Age 40 : Income 460000
    4 : Wgeecnce : Age 43 : Income 370000
    and so on.
    These three pieces of data, Name,Age and Income were all generated randomly to be stored in an array of objects of class Person.
    Now what I must do is , read in this very file and re-create the array of objects that they were initially written from.
    I'm totally lost on how to go about doing this, I have only been learning java for the last month so anyone that can lend me a hand, that would be superb!
    Cheers!

    Looking at you other thread, you are able to create the code needed - so what's the problem?
    Here's an (not the only) approach:
    Create an array of the necessary length to hold the 3 variables, or, if you don't know the length of the file, create a class to contain the data. Then create an ArrayList to hold an instance of the class..
    Use the Scanner class to read and parse the file contents into the appropriate variables.
    Add each variable to either the array, or to an instance of the class and add that instance to the arraylist.

  • After downloading 4.0 I get this message: JavaScript application can't create mcafee plug-in object: TypeError: components.classes[cid] is undefined

    I finished downloading Firefox 4.o to my Mac OS.X.
    When I try to open a website I get the message:
    [JavaScript Application] can't create mcafee plug-in object: TypeError: Components.classes[cid] is undefined
    If I click the OK button, the site opens, but without the McAfee alert at the bottom of the window.
    I had just downloaded 3.6.16, and got box suggesting download version 4.0 for better security, but that seems to be where the problem is!

    That indicates that an add-on you are using is not compatible, considering the other errors it is possibly the McAfee add-on. To confirm what add-on is causing this use the procedure in this link - https://support.mozilla.com/kb/Troubleshooting+extensions+and+themes

  • Can't create mcafee plug-in object: TypeError: Components.classes[cid] is undefined

    I updated to Firefox 4.0 and ever since then, I get this message when I try to open Firefox:
    can't create mcafee plug-in object: TypeError: Components.classes[cid] is undefined
    I have a Mac and have McAfee protection for Mac. This problem did not happen before I updated Firefox. Once I click on "OK" Firefox opens.

    This issue is most likely caused by a McAfee extension that isn't working properly and you will have to disable the extension that causes it.
    You can also check if there is an update available from McAfee that fixes this problem.

  • The following error message came when I tried to open Firefox and install Firefox Home. "can't create mcafee plug-in object: TypeError: Components.classes[cid] is undefined"

    The following error message came when I tried to open Firefox and install Firefox Home.
    "can't create mcafee plug-in object: TypeError: Components.classes[cid] is undefined"

    This issue can be caused by an extension or plugin that isn't working properly.
    Start Firefox in [[Safe Mode]] to check if one of the add-ons is causing the problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    * Don't make any changes on the Safe mode start window.
    See:
    * [[Troubleshooting extensions and themes]]
    * [[Troubleshooting plugins]]

  • How to create an Array of Object

    Is this correct:
    Object[] anArray = new Object[5];
    Thanks.

    Your code will create an array of 5 null references to class Object. After that line you could code:anArray[0] = new Integer(5);- or -
    Object x = anArray[1];but if you code:anArray[3].DoSomething();and have not initialized anArray[3], you will get a NullPointerException.
    Doug

  • Creating an array of objects sets them all to null?

    I am using the following code:
    public class PlayerTest {
        public static void main(String[] args) {
            Player[] p = new Player[1];
            System.out.println(p[0].getId());
    }and for the 'Player' object:
    public class Player {
        int id;
        String name;
        int prediction;
        int score;
        public Player() {
            this.name = "a";
            this.score = -1;
            this.id = genRanId();
            this.prediction = -1;
    ...and, when i try to execute the "PlayerTest" class, i get the error:
    Exception in thread "main" java.lang.NullPointerException
            at PlayerTest.main(PlayerTest.java:5)I think this is because when the array of player objects is created, they are all set to null, and the fields are not created. How do i get the program to initialise the fields in each player object of the array?
    Creating the array of Player objects doesnt seem to use the constructor for the player class like creating an indivdual one does for some reason, as if i create a single element, instead of an array of them, it works fine....
    Please help!

    Yes you are quite right they are null by default (that is nothing is assigned to the array of pointers you have created) you will have t initialise the array the array
            Player[] p = new Player[1];
            for(int i=0;i<p.length;i++)p[i] = new Player();
        //or you can do
       Player[] p = {new Player(),new Player()};(IMHO) Its pointless having an array like this with identical objects you are betteroff instantiating the Person class using a constructor that takes some initial parameters however it is up to you.
    Good luck
    Wiraj

  • Creating new instances of objects from external classes

    Hello!
    I have a number of classes, in particular a 'room' class and a 'player' class. I've just made them as simple classes with a couple of fields and a few accessor and mutator methods.
    I have a 'start' class, and at the moment it has the heading:
    public class start extends room {  This is working fine, as I have been able to create an array of rooms and use the room object's roomName method for each room to name it. But now I also want to create a new player:
    player player1 = new player;But I don't know how to do that. I'm fairly new to Java and have been working from web tutorials and textbooks, but am still not quite used to the very 'universal' format of the code (i.e it just uses generic terms instead of actual examples of real-life situations).
    If someone can help me with a simple way of having both the room and player class available for new object creation I'd be most grateful. My compiler cannot seem to create the new player as there is no direct link to that class.
    Cheers.
    Hussein.
    "Simplicity is appreciated."

    You keep posting these basic questions and asking for simple answers. Well, learning Java is not a simple task. You need to start at the beginning of a long road and take many steps, one at a time. May I suggest one or more of the following:
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.
    James Gosling's The Java Programming Language. Gosling is
    the creator of Java. It doesn't get much more authoratative than this.

  • Creating an array of objects

    Hey,
    I basically have two classes and am trying to create an array of one class in the sub class. My code keeps coming up with <identifier> expected on complie:
    Main Class
    import java.util.ArrayList;
    import java.io.*;
    * @author David Bainbridge
    * @Date 12/02/07
    public class Main {
             public ArrayList<City>ListOfCities;
    public static void main(String[] arguments) {
         Main.newcity();
         public Main() {
         ListOfCities = new ArrayList<City>(); //this creates an array which stores all instances of the cities.
         public static void newcity() {
              String Name = "Lincoln";
              String Lat = "10";
              String Long = "11";         
              ListOfCities.add(new City(Name, Lat, Long)); 
              Lincoln.displaycity();
    }City Class
      * The City class represents a City.
      * @author David Bainbridge
      * @Date 13/02/07
    public class City {
         private String Name;
         private String Latitude;
         private String Longitude;
          * Constructor for the City.
         public City(String cityName, String cityLat, String cityLong) {
              Name = cityName;
              Latitude = cityLat;
              Longitude = cityLong;          
          * Display the current City.
    public void displaycity() {
              System.out.println("Name: " + Name);
              System.out.println("Latitude: " + Latitude);
              System.out.println("Longitude: " + Longitude);
    }

    Thanks JJCoolB but neither worked!
    I have rejigged my code:
    import java.util.ArrayList;
    import java.io.*;
    * @author David Bainbridge
    * @Date 12/02/07
    public class Main {
             public static ArrayList<City>ListOfCities;
    public static void main(String[] arguments) {
         ListOfCities = new ArrayList<City>(); //this creates an array which stores all instances of the cities.
         Main.newcity();
         public static void newcity() {
              String Name = "Lincoln";
              String Lat = "10";
              String Long = "11";         
              ListOfCities.add(new City(Name, Lat, Long)); 
              Lincoln.displaycity();
    }I get two complie errors with it one says:
    public static ArrayList<City>ListOfCities; - <identifier> expected
    ListOfCities = new ArrayList<City>(); //this creates an array which stores all instances of the cities. - '(' or '[' expected.
    Thanks in advance for any help people!

  • Forwarding the array of object to servlet class

    Hi
    i am new to this j2ee.So please cooperate with me.
    i am having an array of objects in a jsp page.
    Each object represent a option which could be seelected through radio button.
    Now i want to send one selected object,corresponding to selected radio button to my servlet ManageUser.
    how can i do that.can any one help me please.
    i have been trying like this but i guess it is not correct .
    <%--   
    --%>   
    <%@page contentType="text/html" pageEncoding="UTF-8"%>    
    <%@page import="abc.javabean.EmpJavaBean"%>  
    <!--importing pages(classes) to implement request response  -->  
    <%@page import="javax.servlet.ServletException"%>  
    <%@page import="javax.servlet.http.HttpServlet"%>  
    <%@page import="javax.servlet.http.*"%>  
    <%@page import="javax.servlet.RequestDispatcher"%>  
    <%@page import="java.util.*"%>  
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
       "http://www.w3.org/TR/html4/loose.dtd">    
    <html>  
        <head>  
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
            <title>JSP Page</title>  
            <script type="text/javascript">  
                //function for selecting the radio  
                function validateRadio(fetchedArrayObject)  
                    alert("hi");  
                    var thisone=-1;  
                    for(i=0;i<document.searchedEmpForm.radioGroup.length;i++)  
                            if(searchedEmpForm.radioGroup.checked==true)
    thisone=i;
    alert(thisone);
    var name=fetchedArrayObject[i].getEmpName();
    alert(name);
    session.setAttribute("fetchedArrayObject[i]",fetchedArrayObject[i]);
    if(thisone==-1)
    alert("you must select a radio Button");
    return false;
    return true;
    </script>
    </head>
    <body bgcolor="#8db6cd">
    <!--retreaving the array values from the servlet -->
    <%
    //int a;
    EmpJavaBean fetchedArrayObject[]=new EmpJavaBean[4];
    fetchedArrayObject=(EmpJavaBean[])request.getAttribute("substituteArray");
    //a=fetchedArrayObject[0].getEmpNumber();
    %>
    <h3>ur new no is <%=fetchedArrayObject[0].getEmpNumber()%></h3><br>
    <form name="searchedEmpForm" action="/Precize/ManageUser" onsubmit="return validateRadio(fetchedArrayObject)">
    <br></br>
    <h2 align="center">Your Searched Result Is Here</h2>
    <br></br>
    <table border="1" align="center">
    <thead>
    <tr>
    <th> </th>
    <th> <input type="button" value="Emp#" name="searchedPageEmpNumb"> </th>
    <th> <input type="button" value="Name" name="searchedPageEmpName"> </th>
    <th> <input type="button" value="Priv" name="searchedPageEmpPriv"> </th>
    <th> <input type="button" value="Role" name="searchedPageEmpRole"> </th>
    <th> <input type="button" value="Start Date" name="searchedPageEmpStartDate"> </th>
    <th> <input type="button" value="End Date" name="searchedPageEmpEndDate"> </th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td><input type="radio" name="radioGroup" value="r11" ></td>
    <td><%=fetchedArrayObject[0].getEmpNumber()%></td>
    <td><%=fetchedArrayObject[0].getEmpName()%></td>
    <td><%=fetchedArrayObject[0].getEmpPrivilege() %></td>
    <td><%=fetchedArrayObject[0].getEmpRole()%></td>
    <td><%=fetchedArrayObject[0].getEmpStartdate()%></td>
    <td><%=fetchedArrayObject[0].getEmpEndDate() %></td>
    </tr>
    </tbody>
    </table>
    <br><center><input type="submit" value="Update" name="updateButton" ></center>
    <h3 align="center">Select the Employee To be Updated/deleted</h3>
    </form>
    </body>
    </html>
    please suggest me the answer.
    regards
    thanx                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I think you need to learn the difference between "java" and "javascript"
    calling session.setAttribute from a javascript function will not have the effect that you desire.
    If you give all radio buttons the same "name", then request.getParameter("radioGroup") should tell you the value of the selected one.

  • Create an array of objects

    i have to write a program with 3 classes, Student, Coarse, and Main.
    Coarse class has 3 instance variables, with the constructor:
    public Coarse(String symbol, String name, int credit)Student class has 3 instance variables plus one method, one of these variables is an array of class Coarse, if i write a constructor of Coarse-class in Student, i would limit the number of coarses to one.
    Coarse coarse=new Coarse("CMPE112", "OOP", "3");i want the student to input all the coarses he signed in???

    noowa wrote:
    i want the student to input all the coarses he signed in???How do you want them to input their courses? If this is a dynamically-sized array, then instead of using an Array, go for an ArrayList. Then find some way to get user input (if that's what you wanted) and then instantiate new course objects into the ArrayList.
    Arrays: http://java.sun.com/docs/books/tutorial/reflect/special/index.html
    Lists: http://java.sun.com/docs/books/tutorial/collections/implementations/list.html
    ArrayList: http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
    As for input, there are many, many options. Common ones are use the BufferedReader, InputStreamReader, and Scanner classes.
    There are some solutions here: http://forum.java.sun.com/thread.jspa?threadID=555025&messageID=2724272
    I'm not fully comprehending your question. Care to give some surrounding code or information?

  • Error message when opening FF: can't create mcafee plug-in object: TypeError: Components.classes[cid] is undefined

    I can click ok and firefox will open, but it's still odd... I get the same message when opening any kind of pop-up window.

    This issue is most likely caused by a McAfee extension that isn't working properly and you will have to disable the extension that causes it.
    You can also check if there is an update available from McAfee that fixes this problem.

  • Creating array of objects of JLabel , JTextField type

    hello,
    I wanted to create an array of objects of JLabel class. I wrote and complied the following lines. it was successfully compiled but during execution it showed - 'start: applet not initialized' on the applet's window. What wrong have I done and how can I get rid of that?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    /*<html>
    <applet code="test.class" width=200 height=300>
    </applet>
    </html> **/
    public class test extends JApplet
         Container c = getContentPane();
         JLabel lb[];
         public void init()
                   for( int i = 0; i < 10; i++ )
                   lb[i] = new JLabel( "Line" + i );
                   c.add( lb[i] );
    }

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    /*<html>
    <applet code="test.class" width=200 height=300>
    </applet>
    </html> **/
    public class test extends JApplet
         Container c = getContentPane();
         JLabel lb[] = new JLabel[10];
         public void init()
                   for( int x = 0; x < 10; x++ )
                   lb [x]= new JLabel( "Line" + x );
                   c.add( lb );
    // showing applet not initiliazed
    // generating nullPointerException
    // please helpLast post, thats a promise!!! :-)Still wrong. See corrections in 'for' loop. :)

Maybe you are looking for

  • HP LaserJet 1018 has a paper output jam, but i found nothing

    Hi.         My HP LaserJet 1018 has a pop-up window: The HP LaserJet 1018 has a paper output jam. Please follow the instructions below"... I did took the print cartridge out, but I see nothing(no paper) inside. And error still occur. What can I do?

  • How to list the files in a directory which are recently modififed few mins

    Hi, I need command to list the files in a directory which are modified few minutes ago in SunOS. like "find . -cmin 2 -print " which list files that are modified 2 mins ago in Linux platform. Thanks in advance. sudha85

  • Can we make apply  join a column on which VPD policy applied in Oracle 10g

    Hi, i am planning to apply a column level security using VPD concept into Oracle 10g but i have a one doubt. Suppose i am going to apply a VPD policy based on user priviliges on a column DEPTNO in EMP table so whenever a particular user logs in,he wi

  • Can I Create An Auto Tone Plus Half Stop Preset?

    In Lightroom 2+ I really love the new Auto Tone, it gets me much closer, much faster. However, I'm wondering if there is anyway to (probably with a text editor) create a preset like do Auto Tone and then add .25 exposure. Should I be looking at a dif

  • Corrupt file prevents installation

    I recently re-installed Win XP on my (old) computer. When I go to re-install my Premiere Elements using the original installation CD the installation fails with: Error 1335 Data1.cab file required for this installation is corrupt and cannot be used.