IllegalArgumentException with Constructor.newInstance

Hi,
I am having problem in the following piece of code . Its giving exception at code line
Servant tieInstance = (Servant) tieConstructor.newInstance(constructorArgs);
Can you plz let me know what might be the problem.
private Servant createTie()
String className = getClassNameForTie();
className = className.substring(className.lastIndexOf(46) + 1, className.length() - 4);
String tieName = getTieClassPackage() + "." + className +
     TIE_CLASSNAME_POSTFIX;
try
Class tieClass = Class.forName(tieName);
Constructor tieConstructor = tieClass.getDeclaredConstructors()[0];
Object constructorArgs[] = new Object[2];
constructorArgs[0] = this;
constructorArgs[1] = PDMEServer.getTheRootPOA();
System.out.println("00000 constructorArgs[0]= " + constructorArgs[0]);
System.out.println("11111 constructorArgs[1]= " + constructorArgs[1]);
Servant tieInstance = (Servant) tieConstructor.newInstance(constructorArgs);
return tieInstance;
catch(ClassNotFoundException ex)
MappingFaultHandler.unexpectedException(this, ex, false);
catch(IllegalAccessException ex)
MappingFaultHandler.unexpectedException(this, ex, false);
catch(InstantiationException ex)
MappingFaultHandler.unexpectedException(this, ex, false);
catch(InvocationTargetException ex)
MappingFaultHandler.unexpectedException(this, ex, false);
catch(IllegalArgumentException ex)
{   System.out.println("*********** IllegalArgumentException caught");
MappingFaultHandler.unexpectedException(this, ex, false);
return null;
}

what does the constructor for the class that getClassNameForTie() names look like?

Similar Messages

  • Problems with constructors

    Hi guys im having problems with constructors. I get the following error:
    package\Cat5500IfXDescr.java:60: cannot resolve symbol
    symbol : constructor IfXDescrScanner(java.net.Inet,java.lang.String,java.lang.String,differentPackage.SNMPCommandObserver)
    location: class package.IfXDescrScanner
    super( InetAddress.getByName( device.getIpAddress()),
    I have a class SNMPCommand
    I have a class IfDescrScanner which extends SNMPCommand
    I have a class Cat5500IfXDescr which extends IfDescrScanner
    Here are the respective constructors:
         public SNMPCommand( InetAddress agentAddress, String readCommunityString,
                                  String writeCommunityString, SNMPCommandObserver observer ){
              peer = new SnmpPeer( agentAddress );
              peer.getParameters().setReadCommunity( readCommunityString );
              peer.getParameters().setWriteCommunity( writeCommunityString );
              this.observer = observer;
         public SNMPCommand( InetAddress agentAddress, SNMPCommandObserver observer ){
              peer = new SnmpPeer( agentAddress );
              this.observer = observer;
         public IfXDescrScanner(Device device, SNMPCommandObserver observer )
         throws UnknownHostException{
              super(      InetAddress.getByName( device.getIpAddress()),
                        device.getReadCommunityString(),
                        device.getWriteCommunityString(),
                        observer );
        public Cat5500IfXDescr( Device device, SNMPCommandObserver observer )
         throws UnknownHostException{
              super(      InetAddress.getByName( device.getIpAddress()),
                        device.getReadCommunityString(),
                        device.getWriteCommunityString(),
                        observer );
         }You'll notice SNMPCommand has 2 constructors. i get no error when i call super to the SNMPCommand constructor from IfXDescrScanner however when i call it from Cat5500IfXDescr i get the error. Is what i am doing illegal. Anyone any ideas on how i solve this. Thanks
    Joe.

    From what I see in a single look, you are passing an object of java.net.Inet to the constructor and the constructor takes InetAddress object as parameter.
    Just check it.
    Hi guys im having problems with constructors. I get
    the following error:
    package\Cat5500IfXDescr.java:60: cannot resolve
    symbol
    symbol : constructor
    IfXDescrScanner(java.net.Inet,java.lang.String,java.la
    ng.String,differentPackage.SNMPCommandObserver)
    location: class package.IfXDescrScanner
    super( InetAddress.getByName(
    device.getIpAddress()),
    I have a class SNMPCommand
    I have a class IfDescrScanner which extends
    SNMPCommand
    I have a class Cat5500IfXDescr which extends
    IfDescrScanner
    Here are the respective constructors:
         public SNMPCommand( InetAddress agentAddress,
    String readCommunityString,
    String writeCommunityString,
    tring, SNMPCommandObserver observer ){
              peer = new SnmpPeer( agentAddress );
    peer.getParameters().setReadCommunity(
    y( readCommunityString );
    peer.getParameters().setWriteCommunity(
    y( writeCommunityString );
              this.observer = observer;
    public SNMPCommand( InetAddress agentAddress,
    , SNMPCommandObserver observer ){
              peer = new SnmpPeer( agentAddress );
              this.observer = observer;
         public IfXDescrScanner(Device device,
    SNMPCommandObserver observer )
         throws UnknownHostException{
    super(      InetAddress.getByName(
    e( device.getIpAddress()),
                        device.getReadCommunityString(),
                        device.getWriteCommunityString(),
                        observer );
        public Cat5500IfXDescr( Device device,
    SNMPCommandObserver observer )
         throws UnknownHostException{
    super(      InetAddress.getByName(
    e( device.getIpAddress()),
                        device.getReadCommunityString(),
                        device.getWriteCommunityString(),
                        observer );
         }You'll notice SNMPCommand has 2 constructors. i get
    no error when i call super to the SNMPCommand
    constructor from IfXDescrScanner however when i call
    it from Cat5500IfXDescr i get the error. Is what i am
    doing illegal. Anyone any ideas on how i solve this.
    Thanks
    Joe.

  • How to instantiate classes at run time with constructors having arguments?

    I have to instantiate some classes in the run-time because they are plugins. The name of the plugin (pluginClassName) comes from a configuration file.
    Currently I am doing this to achieve it:-
    UIPlugin plugin = (UIPlugin)Class.forName(pluginClassName).newInstance();However, there is a disadvantage. I can not pass arguments to the constructor of the plugin.
    public class RainyTheme extends UIPlugin {
      public RainyTheme() {
       // bla bla
      public RainyTheme(int x, int y , int width, int height) {
       // set co-ordinates
       // bla bla
      // bla bla bla bla
    }Now if I want to instantiate this plugin at runtime and at the same time I want to pass the 4 arguments as shown in the second constructor, how can I achieve this?

    I have no experience with JME and the limitations of its API, but looking at the API docs ( http://java.sun.com/javame/reference/apis.jsp ) it seems that there are two main versions, CLDC and CDC, of which CLDC is more limited in its API.
    The Class class does not contain the methods getConstructor(Object[]) or getConstructors() in this version ( http://java.sun.com/javame/reference/apis/jsr139/java/lang/Class.html ), so it seems that if you are using CLDC then there is no way to reflectively call a constructor with parameters. You'd have to find another way to do what you want, such as use the noarg constructor then initialise the instance after construction.

  • How to use Constructor.newInstance(Object [] o)

    this is my code:
    Constructor[] theConstructors = c.getConstructors();
    for(int ii=0;ii<theConstructors.length;ii++)
    Object oArg[] = new Object[2];
    Integer integerX = new Integer(x);
    Integer integerY = new Integer(y);
    oArg[0] = integerX;
    oArg[1] = integerY;
    Class [] cAry =theConstructors[ii].getParameterTypes();
    try{
    o = theConstructors[ii].newInstance(oArg);
    }catch (InstantiationException aa){}
    catch (IllegalAccessException bb){}
    catch (IllegalArgumentException cc){}
    catch (InvocationTargetException dd){}
    and the class called UseCase(Object[] o)
    but the object can't create..is null ......why?

    but the object can't create..is null ......why?Because the constructor wants one parameter of the type Object[], but you give it two parameters of the types Integer.
    Change the following three lines accordingly:
    Object[][] oArg = new Object[1][2];
    oArg[0][0] = integerX;
    oArg[0][1] = integerY;- Marcus

  • Problem with constructors and using public classes

    Hi, I'm totally new to Java and I'm having a lot of problems with my program :(
    I have to create constructor which creates bool's array of adequate size to create a sieve of Eratosthenes (for 2 ->n).
    Then it has to create public method boolean prime(m) which returs true if the given number is prime and false if it's not prime.
    And then I have to create class with main function which chooses from the given arguments the maximum and creates for it the sieve
    (using the class which was created before) and returns if the arguments are prime or not.
    This is what I've written but of course it's messy and it doesn't work. Can anyone help with that?
    //part with a constructor
    public class ESieve {
      ESieve(int n) {
    boolean[] isPrime = new boolean[n+1];
    for (int i=2; i<=n; i++)
    isPrime=true;
    for(int i=2;i*i<n;i++){
    if(isPrime[i]){
    for(int j=i;i*j<=n;j++){
    isPrime[i*j]=false;}}}
    public static boolean Prime(int m)
    for(int i=0; i<=m; i++)
    if (isPrime[i]<2) return false;
    try
    m=Integer.parseInt(args[i]);
    catch (NumberFormatException ex)
    System.out.println(args[i] + " is not an integer");
    continue;
    if (isPrime[i]=true)
    System.out.println (isPrime[i] + " is prime");
    else
    System.out.println (isPrime[i] + " is not prime");
    //main
    public class ESieveTest{
    public static void main (String args[])
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    new ESieve(maximum);
    for(int i=0; i<args.length; i++)
    Prime(i);}

    I've made changes and now my code looks like this:
    public class ESieve {
      ESieve(int n) {
       sieve(n);
    public static boolean sieve(int n)
         boolean[] s = new boolean[n+1];
         for (int i=2; i<=n; i++)
    s=true;
    for(int i=2;i*i<n;i++){
    if(s[i]){
    for(int j=i;i*j<=n;j++){
    s[i*j]=false;}}}
    return s[n];}
    public static boolean prime(int m)
    if (m<2) return false;
    boolean x = sieve(m);
    if (x=true)
    System.out.println (m + " is prime");
    else
    System.out.println (m + " is not prime");
    return x;}
    //main
    public class ESieveTest{
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    public static void main (String[] args)
    int n; int i, j;
    for(i=0;i<=args.length;i++)
    n=Integer.parseInt(args[i]);
    int maximum=max(args[]);
    ESieve S = new ESieve(maximum);
    for(i=0; i<args.length; i++)
    S.prime(i);}
    It shows an error for main:
    {quote} ESieveTest.java:21: '.class' expected
    int maximum=max(args[]); {quote}
    Any suggestions how to fix it?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem with constructor of inner class.

    Hi everybody!
    I have an applet which loads images from a database.
    i want to draw the images in a textarea, so i wrote an inner class, which extends textarea and overrides the paint method.
    but everytime i try to disply the applet in the browser this happens:
    java.lang.NoClassDefFoundError: WohnungSuchenApplet$Malfl�che
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:1590)
    at java.lang.Class.getConstructor0(Class.java:1762)
    at java.lang.Class.newInstance0(Class.java:276)
    at java.lang.Class.newInstance(Class.java:259)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:567)
    at sun.plugin.AppletViewer.createApplet(AppletViewer.java:1778)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:496)
    at sun.applet.AppletPanel.run(AppletPanel.java:293)
    at java.lang.Thread.run(Thread.java:536)
    so my class has no own constructor, it just has the paint method overwritten.
    my class looks like this:
    public class Malfl�che extends javax.swing.JTextArea{
    public void paint(Graphics g){
    Color grey=new Color(220,220,220);
    g.drawImage(img,10,10,null);
    how should a constructor for this class look like?
    sorry i am quite new to this, so i really dont have a clue!
    my class does not have any attributes or requires any so it doesnt need a constructor, doesnt it?
    thanks a lot
    tim

    First off, unlike regular classes, inner classes can be declared public, private, protected, and default.
    Secondly, why are you using the JTextArea to display an image, why not use a JLabel, which takes an Image object as its constructor.
    Thirdly, when you drew your image you did not give it a width and height
    g.drawImage(img, 0,0, img.getWidth(null), img.getHeight(null), null);
    otherwise it will make your image 1 X 1 pixels. not big enough to see.

  • Invalid stored Object Types with Constructor Function

    hi folks,
    i created a stored object type on database 10.2. but it is invalid.
    it has a constructor function and a number of member functions.
    SQLPlus the only feddback is
    Warning: Type Body is compiled with errors.
    Toad 9.0.0 gives no error message.
    how can i find out what kind of error there is? and where?
    thx for help
    joerg

    In SQL*Plus, when you get a warning that you've created an object with compilation errors, you can type
    SQL> show errorsto see the list of errors.
    Justin

  • Java.lang.InstantiationException when using Action class with constructor

    Hi everyone,
    I'm using the insertNewNode() method from this class in another action class, which works fine. But when this action itself is called, I get an infinite java.lang.InstantiationException (until the stack is overflowed). I'm initiating the fields required in every method in a constructor. If there is no constructor, this action works fine again. What's wrong?
    public class GliederungNewAction implements Action {
         private final String DEFAULT_DESCRIPTION = "Neuer Punkt";
         private OracleConnection connection;
         private String username;
         private String catalogue;
         private String attribute;
         private String parent_attr;
         private int parent_sequenceNr;
         private int requiredSequenceNumber;
         public GliederungNewAction(OracleConnection connection, String username, String catalogue) {
              this.connection = connection;
              this.username = username;
              this.catalogue = catalogue;
         public String perform(ActionMapping mapping, HttpServletRequest request,
                   HttpServletResponse response) {
              HttpSession session = request.getSession();
              // fetch the necessary parameters from the JSP site
              // the parent attribute is the selected attribute!
              parent_attr = request.getParameter("attr");
              catalogue = request.getParameter("catalogue");
              parent_sequenceNr = Integer.parseInt(request.getParameter("sort_sequence"));
              username = session.getAttribute("username").toString().toUpperCase();
              // connect to database    
              db.SessionConnection sessConn = (db.SessionConnection) session.getAttribute("connection");
              if (sessConn != null) {
                   try {
                        sessConn.setAutoCommit(false);
                        connection = (OracleConnection)sessConn.getConnection();
                        // insert the new node into DB
                        insertNewNode(DEFAULT_DESCRIPTION, parent_attr, parent_sequenceNr);               
                        connection.commit();
                        // set attributes for JSP post-action operations
                        request.setAttribute("attr", attribute);
                        request.setAttribute("parent_attr", parent_attr);
                   } catch(SQLException ex) {
                        if ( ex.getErrorCode() == 20001 ) {
                             return "error_edit.do";
                        } else { // for all other error codes, rollback and return general error page
                             try {
                                  connection.rollback();
                                  ex.printStackTrace();
                                  return "error_general.do";
                             } catch (SQLException e) {
                                  System.err.println("Rollback failed!");
                                  e.printStackTrace();
                                  return "error_general.do";
                             } // end of catch     
                        } // end of else
                   } // end of catch
              return mapping.getForward();
            // sample method
          * Creates, fills and executes a prepared statement to insert a new entry into the specified table, representing
          * a new node in the catalogue.
          * @param parent_attr TODO
          * @param parent_sequenceNr TODO
          * @throws SQLException
         public void insertNewNode(String description, String parent_attr, int parent_sequenceNr) throws SQLException {
                   requiredSequenceNumber = getRequiredSequenceNumber(parent_attr, parent_sequenceNr);
                   int freeSequenceNumber = getFreeSequenceNumber(requiredSequenceNumber);
                   int lastPosition = getLastNodePosition( getLastChildAttribute(parent_attr) );
                   attribute = createNewNodeAttribute(parent_attr, lastPosition);
                   String callAddNode = "{ call package.addNode(:1, :2, :3, :4, :5, :6, :7) }";
                   CallableStatement cst;
                   cst = connection.prepareCall(callAddNode);
                   cst.setString(1, username );
                   cst.setString(2, catalogue);
                   cst.setString(3, attribute);
                   cst.setString(4, parent_attr);
                   cst.setString(5, description);
                   cst.setInt(6, requiredSequenceNumber);
                   cst.setInt(7, freeSequenceNumber);
                   cst.execute();
                   cst.close();
    java.lang.InstantiationException: action.GliederungNewAction
         at java.lang.Class.newInstance0(Unknown Source)
         at java.lang.Class.newInstance(Unknown Source)
         at action.ActionMapping.perform(ActionMapping.java:54)
         at ControllerServlet.doResponse(ControllerServlet.java:92)
         at ControllerServlet.doPost(ControllerServlet.java:50)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:679)
         at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:431)
         at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:355)
         at ControllerServlet.doResponse(ControllerServlet.java:103)
         at ControllerServlet.doPost(ControllerServlet.java:50)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         .......

    You're welcome.
    Still, I would report this as a bug at the Struts mailinglist/issuetracker. This silly behaviour shouldn't happen. Once an InstantiationException, okay, but in an infinite loop?!? That's definately a bug. Also the detail message may be more informative, e.g. "No default constructor found" or so.

  • Help with constructors, accessors and mutators

    Hi all...
    Can anyone give me a code for the following problem with the use of constructors, accessors and mutators ?
    Programme is :
    Create a class called Stock that has the following attributes:
    STKID : integer
    DESC : STRING
    COSTPRICE : float
    SALEPRICE : float
    QTY : integer
    Create constructors, accessors and mutators for the above class.
    Create an array of object that can store up to 100 of the above objects.
    Implement the following functionalities:
    Add new Stock Record
    Search Stock Record
    Delete Stock Record
    Update Stock Record
    Its quite urgent, since I got to submit this for my interview tomorrow. So if anyone knows the code please do reply. Thanks in advance.
    Thanks and Regards,
    Jayanth.

    @jayanth: Ignore these guys - they're just sour and don't understand the value of helping each other out. Besides, I'm bored, and this was an easy write-up. I can send the code to your email ([email protected]) if you'd like. Just let me know.

  • Problem with constructor

    Hi guys
    when i created this constructor, it keep throwing back this error whcih i don't understand.
    public interface MyNumber {
    // data defination
         private int wholenumber = 0;
         private float fraction = 0;
    // constructor
    public MyNumber(int whole, float fract) {
         wholenumber = whole;
         fraction = fract;
    may i know what is wrong with my constructor code?
    it keep saying <identifier>> expected

    part b of the question has ask for an interface class
    any problem with my code?
    public class MyNumber {
    // data defination
         private int wholenumber = 0;
         private float fraction = 0;
    // constructor
    public MyNumber(int whole, float fract) {
         wholenumber = whole;
         fraction = fract;
    // methods or operations
         public MyNumber add(MyNumber c, MyNumber d){
              int r = wholenumber + c.getWholeNumber();
              float i = fraction + c.getFraction();
              MyNumber newC = new MyNumber(r,i);
              //MyNumber newD = new MyNumber(i);
              return newC;
              //return newD;
         public MyNumber subtract(MyNumber c, MyNumber d){
              int r = wholenumber - c.getWholeNumber();
              float i = fraction - c.getFraction();
              MyNumber newC = new MyNumber(r,i);
              //MyNumber newD = new MyNumber(i);
              return newC;
              //return newD;
         public MyNumber multiply(MyNumber c, MyNumber d){
              int r = wholenumber * c.getWholeNumber();
              float i = fraction * c.getFraction();
              MyNumber newC = new MyNumber(r,i);
              //MyNumber newD = new MyNumber(i);
              return newC;
              //return newD;
         public int getWholeNumber(){
              return wholenumber;
         public float getFraction(){
              return fraction;
    }

  • Object type with constructor gets PLS-00307 (10g)

    Hi all,
    I have the following code, and I am getting the following error. I want to have a constructor that can be called without specifying the parameters by name. Is that not possible?
    What am I doing wrong?
    Thanks!
    Error:Error at line 50
    ORA-06550: line 5, column 17:
    PLS-00307: too many declarations of 'TRANSFEROBJECT_O' match this call
    ORA-06550: line 5, column 5:
    PL/SQL: Statement ignoredCode:DROP TYPE TransferObject_o
    CREATE TYPE
        TransferObject_o
    AS OBJECT
        m_objectId  NUMBER(15)
      , m_attribute VARCHAR2(4000)
      , CONSTRUCTOR FUNCTION TransferObject_o
            p_objectId  NUMBER--   := NULL
          , p_attribute VARCHAR2-- := NULL
        ) RETURN SELF AS RESULT
    CREATE TYPE BODY
        TransferObject_o
    AS
        CONSTRUCTOR FUNCTION TransferObject_o
            p_objectId  NUMBER--   := NULL
          , p_attribute VARCHAR2-- := NULL
        ) RETURN SELF AS RESULT
        IS
        BEGIN
            SELF.m_objectId  := p_objectId;
            SELF.m_attribute := p_attribute;
            RETURN;
        END;
    END;
    DECLARE
        l_object TransferObject_o;
    BEGIN
        l_object := TransferObject_o(1, 'B');
    END;
    /

    Hi,
    When you create an OBJECT, Oracle automatically creates a constructor with one argument for each of the object's attributes. You've created a second constructor, that has the same signature, except that the arguments in your functin are optional. When you call an overloaded routine ( whether it's a constructor or any other function or procedure), Oracle has to decide which of the versions you're calling. If you call the TransferObject_o constructor with fewer than two arguments, the system knows you mean the version you wrote, since the default constructor has two required arguments. But when you call the TransferObject_o constructor with exactly two arguments, it has no way of telling which version to use, and raises an error.
    The Oracle 10.1 "PL/SQL User's Guide and Reference" says:
    "You can define your own constructor methods, either overriding a system-defined constructor, or defining a new function with a different signature."
    I couldn't find an example of overriding the constructor (not that I spent a lot of time looking. If you find one, or figure out how to do it, please post an example or a link here.).
    Failing that, you can always give your constructor a different signature (e.g., put the VARCHAR2 argument first).

  • Need help with constructors

    Here is my InventoryMain.java, Inventory.java, and Maker.java.
    I am having trouble with my constructors in Maker.java. Here is the line (this line is at the bottom of my Maker.java)
    Maker r = new Maker(txtfield1[1].getText(),txtfield1[4].getText(), 0.05, Integer.parseInt(txtfield1[2].getText()), txtfield1[3].getText(), Integer.parseInt(txtfield1[5].getText()),
                   Double.parseDouble(txtfield1[6].getText()));here is my error when compiling:
    symbol : constructor Maker(java.lang.String,java.lang.String,double,int,java.lang.String,int,double)
    location: class inventorymain.Maker
    Maker r = new Maker(txtfield1[1].getText(),txtfield1[4].getText(), 0.05, Integer.parseInt(txtfield1[2].getText()), txtfield1[3].getText(), Integer.parseInt(txtfield1[5].getText()),
    1 error
    BUILD FAILED (total time: 0 seconds)
    I have tried all kinds of different orders trying to match my constructors for Inventory(). Nothing seems to work. Can anyone help????
    InventoryMain.java
    package inventorymain;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    import javax.swing.JFrame;
    public class InventoryMain
        // main method begins execution of java application
        public static void main(String[] args)
            //variables
            double restockFee = 0.05;
            //create array for products in inventory
            //enter elements into array
            Maker p = new Maker( 5186521, "pens", 1.59, 346, "Bic", restockFee);
            Maker q = new Maker( 9486452, "pencils", .59, 487,"Mead", restockFee);
            Maker r = new Maker( 6317953, "markers", 1.29, 168,"Sharpie", restockFee);
            Maker s = new Maker( 5152094, "paperclips", 1.19, 136,"Dennison", restockFee);
            Maker t = new Maker( 4896175, "glue", .79, 72,"Elmer's", restockFee);
            Maker u = new Maker( 5493756, "tape", .49, 127,"3m", restockFee);
            Maker v = new Maker( 6537947, "paper", 1.79, 203,"Mead", restockFee);
            Maker w = new Maker( 7958618, "staples", 1.19, 164,"Pentech", restockFee);
            Maker x = new Maker( 5679139, "folders", .49, 238,"Mead", restockFee);
            Maker y = new Maker( 7689110, "rulers", .17, 123,"Stanley", restockFee);       
            p.ShowInventory();
         p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         p.setVisible(true);
         p.setSize(520, 490);
          }//end main
    }//end class Inventory____________________________
    Inventory.java
    package inventorymain; //file assigned to inventorymain package
    import javax.swing.JFrame;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.NumberFormat;
    import javax.swing.border.*;
    import java.net.*;
    import java.util.StringTokenizer;
    public class Inventory extends JFrame
            // set variables
            private Container cp = getContentPane();
            private static int itemNum[] = new int[100];
            private static String name[] = new String[100];
            private static int units[] = new int[100];
            private static double price[] = new double[100];      
            private static int i = 0;
            public Inventory()
                setLayout(new FlowLayout());
            public Inventory(int _itemNum, String _name, double _price, int _units)//varibles for constructor
                itemNum[i] = _itemNum;//variable initialized
                name[i] = _name;//variable initialized
                units[i] = _units;//variable initialized
                price[i] = _price;//variable initialized
                i = i + 1;
            // All setters and getters
            public static int getItemNum(int k)
                return itemNum[k];
            public static String getItemName(int k)
                return name[k];
            public static int getItemUnits(int k)
                return units[k]; 
            public static double getItemPrice(int k)
                return price[k];
            public static void setItemNum(int k, int value)
                itemNum[k] = value;
            public static void setItemName(int k, String value)
                name[k] = value;
            public static void setItemUnits(int k, int value)
                units[k] = value;
            public static void setItemPrice(int k, double value)
                price[k] = value;
            public static void DeleteItem(int k)
                for(int j=k; j<getCount()-1; j++)
                    setItemNum(j, getItemNum(j + 1));
                    setItemName(j,getItemName(j+1));
              setItemUnits(j,getItemUnits(j+1));
              setItemPrice(j,getItemPrice(j+1));
                }//end for
                i-=1;
            }//end DeleteItem
            public static int SearchItem(String value)
                int k = -1;
                for(int j=0;j<getCount();j++)
              if(getItemName(j).equals(value))
                        k = j;
                }//end for
                return k;
         }//end SearchItem
            public  static double totalOfInventory(double p, int u)//computes value of all merchandise in inventory
                return p * u;
            }//end method totalOfInventory
            public static void swap(int j, int min)
                String tmp;
                tmp = name[j];
                name[j] = name[min];
                name[min] = tmp;
                int temp = itemNum[j];
                itemNum[j] = itemNum[min];
                itemNum[min]= temp;
                temp = units[j];
                units[j] = units[min];
                units[min] = temp;
                double temp1 = price[j];
                price[j] = price[min];
                price[min]= temp1;
            }//ends swap method
            public double showTotalOfInventory()
                double totalValue = 0;
                for (int j = 0; j < getCount(); j++)
                    totalValue = totalValue + totalOfInventory(price[j], units[j]);
                return totalValue;
            }//end showTotalOfInventory
            public static int getCount()
                return i;
    }// end class Inventory
    class Products
        public static double totalOfInventory(double p, double u, double rf)
            double tOfI = (p * u) + (p * u * rf);
            return (tOfI);
        public static double totalOfRestockFee(double p, double rf)
            double percent = 0;
            percent = (p * 5) / 100;
            return percent;       
    }//end class Products_______________________________
    Maker.java
    package inventorymain;
    import javax.swing.JFrame;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.NumberFormat;
    import javax.swing.border.*;
    import java.net.*;
    import java.util.StringTokenizer;
    class Maker extends Inventory implements ActionListener
    {//begins Class Maker
        static String manufact[] = new String[100];
        static double restockingFee[] = new double[100];
        static int i;
        static double TotalVal;
        static int navItem;
        static Boolean isRecordLoadedFromFile = false;
        private Container cp = getContentPane();
        GridBagConstraints c;
        GridBagConstraints cconstraint;
        Border titledborder;
        JPanel pan;
        String labels[] = {"Product Name:", "Manufacturer:", "Product ID Number:", "Units in Stock:", 
                           "Price Per Unit:                                                      $",
                           "Restocking Fee:                                                   $",
                           "Value of Product in Stock:                                $",
                           "Value of All Merchandise Plus Restocking: $"};
        int len1 = labels.length;
        JLabel lbl[] = new JLabel[len1];
        JTextField txtfield1[] = new JTextField[len1];
        String blabels[] = {"First", "Previous", "Next", "Last"};
        int blen = blabels.length;
        JButton navigate[] = new JButton[blen];
        String cmdlabels[] ={"Load File", "Add", "Modify", "Delete", "Search", "Save","Cancel" };
        int cmdlen = cmdlabels.length;
        JButton cmdbutton[] = new JButton[cmdlen];
        JLabel lblImg;
        File file;
        public String FileName;
        public Maker(int Item_Number, String Item_Name, double Item_Price, int Items_in_Stock, String manufact, double restockingFee)// Constructor for varibles
            super(Item_Number, Item_Name, Item_Price, Items_in_Stock);
            this.manufact[i] = manufact;
            this.restockingFee[i] = restockingFee;
            i = i + 1;
        public static void setManufact(int k, String value)
            manufact[k] = value;
        public static double getRestockFee(int val)
            return restockingFee[val];
        public void ShowInventory()
            setLayout(new FlowLayout());
            GridBagLayout contlayout = new GridBagLayout();//layout for container
            GridBagConstraints cconstraint = new GridBagConstraints();//constraint for container
            GridBagLayout gblayout = new GridBagLayout();//layout for panel
            GridBagConstraints gbconstraint = new GridBagConstraints();
            FileName = "C://dat//inventory.dat";
            try
                String strDirectoy = "C://dat";
                boolean success = (new File(strDirectoy)).mkdir();
                file = new File(FileName);
                success = file.createNewFile();
                //ADD SAVE CANCEL DELETE EXIT
                pan = new JPanel();
                gblayout = new GridBagLayout();
                gbconstraint = new GridBagConstraints();
                pan.setLayout(gblayout);
                gbconstraint.gridwidth = 1;
                gbconstraint.gridheight = 1;
                gbconstraint.gridy = 0;
                for (int i = 0; i < cmdlen; i++)
                    cmdbutton[i] = new JButton(cmdlabels);
              cmdbutton[i].addActionListener(this);
              gbconstraint.gridx = i;
              pan.add(cmdbutton[i], gbconstraint);
    }//end for
    titledborder = BorderFactory.createTitledBorder("Confirmation");
    pan.setBorder(titledborder);
    //ADD PANEL TO CONTAINER
    cconstraint.gridwidth = 4;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 0;
    cconstraint.gridy = 2;
    cp.add(pan, cconstraint);
    //ADDITION COMPLETE
    //first panel
    pan = new JPanel();
    gblayout = new GridBagLayout();
    gbconstraint = new GridBagConstraints();
    pan.setLayout(gblayout);
    for (int i = 0; i < 2; i++)
    for (int j = 0; j < len1; j++)
    int x = i;
    int y = j;
    if (x == 0)
    lbl[j] = new JLabel(labels[j]);
    lbl[j].setHorizontalAlignment(JLabel.LEFT);
    lbl[j].setPreferredSize(new Dimension(250, 15));
    gbconstraint.insets = new Insets(10, 0, 0, 0);
    gbconstraint.gridx = x;
    gbconstraint.gridy = y;
    pan.add(lbl[j], gbconstraint);
    }//end if
    else
    txtfield1[j] = new JTextField(15);
    txtfield1[j].setPreferredSize(new Dimension(300, 15));
    txtfield1[j].setHorizontalAlignment(JLabel.LEFT);
    txtfield1[j].setEnabled(false);
    lbl[j].setLabelFor(txtfield1[j]);
    gbconstraint.gridx = x;
    gbconstraint.gridy = y;
    pan.add(txtfield1[j], gbconstraint);
    }//end else
    }//end for
    }//end for
    Border titledborder = BorderFactory.createTitledBorder("Current Inventory Records");
    pan.setBorder(titledborder);
    //adds panel to container
    cconstraint.gridwidth = 1;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 0;
    cconstraint.gridy = 0;
    cp.add(pan, cconstraint);
    //add icon to display
    pan = new JPanel();
    gblayout = new GridBagLayout();
    gbconstraint = new GridBagConstraints();
    pan.setLayout(gblayout);
    gbconstraint.gridwidth = 1;
    gbconstraint.gridheight = 1;
    gbconstraint.gridy = 0;
    lblImg = new JLabel((new ImageIcon(getClass().getResource("logo111.jpg"))));
    lblImg.setPreferredSize(new Dimension(70, 70));
    pan.add(lblImg);
    cconstraint.gridwidth = 1;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 0;
    cconstraint.gridy = 1;
    cp.add(pan, cconstraint);
    //ends icon insert
    //navigation panel
    pan = new JPanel();
    gblayout = new GridBagLayout();
    gbconstraint = new GridBagConstraints();
    pan.setLayout(gblayout);
    gbconstraint.gridwidth = 1;
    gbconstraint.gridheight = 1;
    gbconstraint.gridy = 1;
    for (int i = 0; i < blen; i++)
    navigate[i] = new JButton(blabels[i]);
    gbconstraint.gridx = i;
    pan.add(navigate[i], gbconstraint);
    navigate[i].addActionListener(this);
    }//end for
    titledborder = BorderFactory.createTitledBorder("Navigation Panel");
    pan.setBorder(titledborder);
    //add panel to container
    cconstraint.gridwidth = 4;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 1;
    cconstraint.gridy = 1;
    cp.add(pan, cconstraint);
    }//end try
    catch (Exception e)
    e.printStackTrace();
    }//end catch
    }//end showInventory
    public void setContents(File aFile, String aContents)
    BufferedWriter output = null;
         try
    //use buffering
    //FileWriter always assumes default encoding is OK!
    output = new BufferedWriter(new FileWriter(aFile, true));
    output.write(aContents);
    String newLine = System.getProperty("line.separator");
    output.write(newLine);
    }//end try
    catch (Exception ex)
    ex.printStackTrace();
    }//end catch
    finally
    try
    //flush and close both "output" and its underlying FileWriter
              if (output != null) output.close();
    }//end try
    catch (java.io.IOException e)
    e.printStackTrace();
    }//end catch
    public void AddModifyInventory(String Mode)
    if (Mode.equals("Insert"))
    String Content = txtfield1[1].getText() + "\t"
    + txtfield1[2].getText() + "\t" + txtfield1[3].getText()
    + "\t" + txtfield1[4].getText();
    setContents(file, Content);
    JOptionPane.showMessageDialog(null, "Record Successfully Inserted");
    }//end if
    }//end AddModifyInventory
    public void ShowInventory(int ItemNo)
    txtfield1[0].setText(Integer.toString(ItemNo));
    txtfield1[0].setText(Inventory.getItemName(ItemNo));
    txtfield1[1].setText(manufact[ItemNo]);
    txtfield1[2].setText(Integer.toString(Inventory.getItemNum(ItemNo)));
    txtfield1[3].setText(Integer.toString(Inventory.getItemUnits(ItemNo)));
    txtfield1[4].setText(Double.toString(Inventory.getItemPrice(ItemNo)));
    txtfield1[5].setText(String.format("%3.2f",
    Products.totalOfRestockFee(Inventory.getItemPrice(ItemNo),
    getRestockFee(ItemNo))));
    txtfield1[6].setText(String.format("%3.2f",
    Products.totalOfInventory(Inventory.getItemPrice(ItemNo),
    Inventory.getItemUnits(ItemNo), getRestockFee(ItemNo))));
    txtfield1[7].setText(String.format("%3.2f", GetTotalInvVal()));
    }//end ShowInventory(int ItemNo)
    public void EnableFields(boolean bflag)
    txtfield1[1].setEnabled(bflag);
    txtfield1[2].setEnabled(bflag);
    txtfield1[3].setEnabled(bflag);
    txtfield1[4].setEnabled(bflag);
    txtfield1[5].setEnabled(bflag);
    }//end EnableFields
    public double GetTotalInvVal()
    TotalVal = 0;
    for(int j = 0; j < Inventory.getCount(); j++)
    TotalVal += Products.totalOfInventory(Inventory.getItemPrice(j),
    Inventory.getItemUnits(j), getRestockFee(j));
    return TotalVal;
    }//end GetTotalInvVal
    public Integer GetRecordCount()
         FileReader fr;
         BufferedReader br;
         LineNumberReader lnr;
         String line;
         int lno = 0;
         try
    lnr = new LineNumberReader(new BufferedReader(new FileReader(FileName)));
    while ((line = lnr.readLine()) != null)
              lno = lnr.getLineNumber();
         lnr.close();
         }//end try
         catch (IOException ioErr)
    System.out.println(ioErr.toString());
    System.exit(100);
         return lno;
    public void showInventory(int itemNo)
    int i;
    FileReader fr;
    BufferedReader br;
    LineNumberReader lnr;
    StringTokenizer st;
    String line;
    int item = itemNo + 1;
    int ItemNo = 0;
    int Units = 0;
    String ItemGenre = "";
    String ItemName = "";
    String ItemRating = "";
    double UnitPrice = 0;
    double Total = 0;
    Integer rFee = 0;
    int lno;
    try
              lnr = new LineNumberReader(new BufferedReader(new FileReader(FileName)));
              while ((line = lnr.readLine()) != null)
    lno = lnr.getLineNumber();
    String s1[];
    if (item == lno)
                   s1 = new String[lno];
                   s1[0] = line;
                   st = new StringTokenizer(s1[0]);
                   //ItemNo = lno;
                   ItemGenre = st.nextToken();                         
                   ItemNo = Integer.parseInt(st.nextToken());
                   ItemName = st.nextToken();
                   ItemRating = st.nextToken();
                   Units = Integer.parseInt(st.nextToken());
                   UnitPrice = Double.parseDouble(st.nextToken());
                   //rFee = Integer.parseInt(st.nextToken());
    }//end if
    s1 = new String[lno];
    s1[0] = line;
    st = new StringTokenizer(s1[0]);
    st.nextToken();
    st.nextToken();
    st.nextToken();
    st.nextToken();
    Integer units = Integer.parseInt(st.nextToken());
    Double price = Double.parseDouble(st.nextToken());
    Total += Products.totalOfInventory(price, units, 0.05);
    }//end while
    lnr.close();
    }//end try
    catch (IOException ioErr)
              System.out.println(ioErr.toString());
              System.exit(100);
    }//end catch
    txtfield1[0].setText(Integer.toString(itemNo));
    txtfield1[0].setText(ItemName);
    txtfield1[1].setText(manufact[ItemNo]);
    txtfield1[2].setText(Integer.toString(ItemNo));
    txtfield1[3].setText(Integer.toString(Units));
    txtfield1[4].setText(Double.toString(UnitPrice));
    txtfield1[5].setText(String.format("%3.2f", Products.totalOfRestockFee(UnitPrice, 0.05)));
    txtfield1[6].setText(String.format("%3.2f", Products.totalOfInventory(UnitPrice, Units, 0.05)));
    txtfield1[7].setText(String.format("%3.2f", Total));          
         }//end showInventory
    public void actionPerformed(ActionEvent e)//button actions
    String btnClicked = ((JButton)e.getSource()).getText();
    if(btnClicked.equals("First"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
              navItem = 0;
              showInventory(navItem);
    }//end if
    else
              navItem = 0;
              ShowInventory(navItem);
    }//end else
         }//end if
         if (btnClicked.equals("Next"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
              if (navItem == GetRecordCount() - 1)
    navItem = 0;
              }//end if
    else
    navItem += 1;
              }//end else
              if ((GetRecordCount() - 1) >= navItem)
    showInventory(navItem);
    else
    showInventory(GetRecordCount() - 1);
    }//end if
    else
    if (navItem == getCount() - 1)
    navItem = 0;
    }//end if
    else
    navItem += 1;
    }//end else
    ShowInventory(navItem);
    }//end else
         }//end if
    if (btnClicked.equals("Previous"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
    if (navItem == 0)
    navItem = GetRecordCount() - 1;
              }//end if
    else
    navItem = navItem - 1;
              }//end else
    showInventory(navItem);
    }//end if
    else
              if (navItem == 0)
    navItem = getCount() - 1;
              }//end if
    else
    navItem = navItem - 1;
              }//end else
    ShowInventory(navItem);
    }//end else
         }//end if
    if (btnClicked.equals("Last"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
    navItem = GetRecordCount() - 1;
              showInventory(navItem);
    }//end if
    else
              navItem = getCount() - 1;
              ShowInventory(navItem);
    }//end else
         }//end if
    if (btnClicked.equals("Save"))
    AddModifyInventory("Insert");
         }//end if
    if (btnClicked.equals("Load File"))
    isRecordLoadedFromFile = true;
    if (GetRecordCount() == 0)
              JOptionPane.showMessageDialog(null, "No Records Found in the File");                    
    }//end if
    else
              showInventory(0);
    }//end else
    if (btnClicked.equals("Cancel"))
              EnableFields(false);
              cmdbutton[4].setText("Search");
              cmdbutton[2].setText("Modify");
              cmdbutton[1].setText("Add");
    if(isRecordLoadedFromFile)
    showInventory(navItem);
              else
    ShowInventory(navItem);
    }//end if
    if(btnClicked.equals("Delete"))
              Inventory.DeleteItem(Integer.parseInt(txtfield1[0].getText()));
              navItem = getCount() -1;
              JOptionPane.showMessageDialog(null, "Record Successfully deleted");
              ShowInventory(navItem);
    }//end if
    if(btnClicked.equals("Search"))
              cmdbutton[4].setText("GO!");
              txtfield1[3].setEnabled(true);     
    }//end if
    if(btnClicked.equals("GO!"))
              boolean valid = true;
    if (txtfield1[3].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Product Name Required");
    valid = false;
              }//end if
    if(valid)
    int k = Inventory.SearchItem(txtfield1[3].getText().trim());
    if(k>=0)
                   txtfield1[0].setText(Integer.toString(k));
                   txtfield1[0].setText(Inventory.getItemName(k));
    txtfield1[1].setText(manufact[k]);
    txtfield1[2].setText(Integer.toString(Inventory.getItemNum(k)));
                   txtfield1[3].setText(Integer.toString(Inventory.getItemUnits(k)));
                   txtfield1[4].setText(Double.toString(Inventory.getItemPrice(k)));
                   txtfield1[5].setText(String.format("%3.2f", Products.totalOfRestockFee(Inventory.getItemPrice(k), getRestockFee(k))));
                   txtfield1[6].setText(String.format("%3.2f", Products.totalOfInventory(Inventory.getItemPrice(k ), Inventory.getItemUnits(k), getRestockFee(k))));
                   txtfield1[7].setText(String.format("%3.2f",GetTotalInvVal()));
                   EnableFields(false);
                   cmdbutton[4].setText("Search");                              
    }//end if
    else
    JOptionPane.showMessageDialog(null, "No Matches found");     
    cmdbutton[4].setText("Search");     
    EnableFields(false);
    }//end else
              }//end if               
    }//end if
    if(btnClicked.equals("Modify"))
              EnableFields(true);                         
              cmdbutton[2].setText("Click to Modify!");
    }//end if
    if(btnClicked.equals("Click to Modify!"))
              Boolean valid = true;
    if (txtfield1[1].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Genre Required");
    valid = false;
              }//end if
    try
    Integer.parseInt(txtfield1[2].getText());
              }//end try
              catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Item Number (Only Numbers allowed)");
    txtfield1[2].setText("");
    valid = false;
              }//end catch
              if (txtfield1[3].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Product Name Required");
    valid = false;
              }//end if
              if (txtfield1[4].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Rating Required");
    valid = false;
              }//end if
              try
    Integer.parseInt(txtfield1[5].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Units in Stock (Only Numbers allowed)");
    txtfield1[4].setText("");
    valid = false;
              }//end catch
    try
    Double.parseDouble(txtfield1[6].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Price (Only Numbers allowed)");
    txtfield1[5].setText("");
    valid = false;
              }//end catch
              if (valid)
    //setItemNum,setItemName,setItemUnits,setItemPrice
    Inventory.setItemNum(navItem,Integer.parseInt(txtfield1[1].getText()));
    Inventory.setItemName(navItem,txtfield1[2].getText());
    Inventory.setItemUnits(navItem,Integer.parseInt(txtfield1[4].getText()));
    Inventory.setItemPrice(navItem,Double.parseDouble(txtfield1[5].getText()));     
    txtfield1[6].setText(String.format("%3.2f", Products.totalOfRestockFee(Inventory.getItemPrice(navItem), getRestockFee(navItem))));
    txtfield1[7].setText(String.format("%3.2f", Products.totalOfInventory(Inventory.getItemPrice(navItem ), Inventory.getItemUnits(navItem), getRestockFee(navItem))));
    txtfield1[8].setText(String.format("%3.2f",GetTotalInvVal()));
    EnableFields(false);
    cmdbutton[2].setText("Modify");
              }//end if
    }//end if
    if (btnClicked.equals("Add"))
              EnableFields(true);
              txtfield1[0].setText(Integer.toString(getCount()));
              txtfield1[1].setText("");
              txtfield1[2].setText("");          
              txtfield1[3].setText("0");
              txtfield1[4].setText("0.00");
              cmdbutton[1].setText("Click to Add!");
    }//end if
    if (btnClicked.equals("Click to Add!"))
    Boolean valid = true;
    try
    Integer.parseInt(txtfield1[2].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Item Number (use numbers only)");
    txtfield1[2].setText("");
    valid = false;
              }//end catch
              if (txtfield1[0].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Product Name Required");
    valid = false;
              }//end if
              try
    Integer.parseInt(txtfield1[3].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Units in Stock (use numbers only)");
    txtfield1[3].setText("");
    valid = false;
              }//end catch
    try

    You do not need to post that massive amount of code to ask about a compile-time error.
    I (and many others here) won't even consider looking at it. Create a small example that demonstrates what you're having trouble with.

  • Method.invoke causes IllegalArgumentException with subclass instance

    Is there a way to use an instance of a subclass when using reflection to invoke a method?
    Given the following code, I want to be able to use reflection to invoke the "doSomething" method within the Foo class. However, I want to use an instance of Bar as the parameter value when using reflection (since an instance of Bar is implicitly an instance of Foo; I have also tried casting the Bar instance, b, to Foo but this does not work). Doing this yields an IllegalArgumentException.
    What am I missing? What am I doing wrong? What do I have to do in order to use an instance of Bar with "invoke"?
    // Foo.java
    package junk;
    public class Foo
        private void doSomething(Foo f)
            System.out.println("Doing something with a " + f.getClass().getName());
        public static void main(String[] args)
            Foo f = new Foo();
            Bar b = new Bar();
            f.doSomething(f);   // Outputs "Doing something with a junk.Foo"
            f.doSomething(b);   // Outputs "Doing something with a junk.Bar"
            Class[] paramTypes = new Class[] { f.getClass() };
            Object[] paramValues = new Object[] { b };
            b.invokePrivateFooMethod("doSomething", paramTypes, paramValues); // Doesn't work
    // Bar.java
    package junk;
    import java.lang.reflect.Method;
    import java.lang.reflect.InvocationTargetException;
    public class Bar extends Foo
        public void invokePrivateFooMethod(String methodName,
                                           Class[] paramTypes,
                                           Object[] paramValues)
            try
                Foo localF = new Foo();
                Class classToUse  = localF.getClass();
                Method methodToUse = classToUse.getDeclaredMethod(methodName, paramTypes);
                methodToUse.setAccessible(true);    // override of private modifier
                methodToUse.invoke(classToUse, paramValues);
            catch (IllegalAccessException e)
                e.printStackTrace();
            catch (NoSuchMethodException e)
                e.printStackTrace();
            catch (InvocationTargetException e)
                e.printStackTrace();
    }

    Sorrry for the confusion. It's always the little things...
    I neglected to use an instance of Foo to invoke the method.
    See corrected code below:
    // Bar.java
    package junk;
    import java.lang.reflect.Method;
    import java.lang.reflect.InvocationTargetException;
    public class Bar extends Foo
        public void invokePrivateFooMethod(String methodName,
                                           Class[] paramTypes,
                                           Object[] paramValues)
            try
                Foo localF = new Foo();
                Class classToUse  = localF.getClass();
                Method methodToUse = classToUse.getDeclaredMethod(methodName, paramTypes);
                methodToUse.setAccessible(true);    // override of private modifier
                // NOTE:  Use localF, NOT classToUse!
                methodToUse.invoke(localF, paramValues);
            catch (IllegalAccessException e)
                e.printStackTrace();
            catch (NoSuchMethodException e)
                e.printStackTrace();
            catch (InvocationTargetException e)
                e.printStackTrace();
    }

  • Help with constructors using inheritance

    hi,
    i am having trouble with contructors in inheritance.
    i have a class Seahorse extends Move extends Animal
    in animal class , i have this constructor .
    public class Animal() {
    public Animal (char print, int maxage, int speed) {
    this.print = print;
    this.maxage = maxage;
    this.speed = speed;
    public class Move extends Animal {
    public Move(char print, int maxage, int speed)
    super(print, maxage, speed); //do i even need this here? if i dont i
    //get an error in Seahorse class saying super() not found
    public class Seahorse extends Move {
    public Seahorse(char print, int maxage, int speed)
    super('H',10,0);
    please help

    It's not a problem, it's how Java works. First, if you do not create a constructor in your code, the compiler will generate a default constructor that does not take any arguments. If you do create one or more constructors, the only way to construct an object instance of the class is to use one of the constructors.
    Second, when you extend a class, your are saying the subclass "is a" implementation of the super class. In your case, you are saying Move is an Animal, and Seahorse is a Move (and an Animal as well). This does not seem like a good logical design, but that's a different problem.
    Since you specified that an Animal can only be constructed by passing a char, int, and int, that means that a Move can only be constructed by calling the super class constructor and passing a char, int, and int. Since Move can only be constructed using a char, int and int, Seahorse can only be constructed by calling super(char, int, int);.
    It is possible for a subclass to have a constructor that does not take the same parameters as the super class, but the subclass must call the super class constructor with the correct arguments. For example, you could have.
    public Seahorse() {
       super('S',2,5);
    }The other problem is, Move does not sound like a class. It sounds like a method. Perhaps you might have MobileAnimal, but that would only make sense if there was a corresponding StationaryAnimal. Your classes should model your problem. It's hard to image a problem in which a Seahorse is a Move, and a Move is an Animal. It makes more sense for Animals to be able to move(), which allows a Seahorse to move differently compared to an Octopus.

  • Problem with JAXBContext.newInstance  internal error

    Hey!
    I am working on an upgrade of the JAXB version in our Enterprise application. Class generation and build apparently works fine. From the class that invokes the webservice I try to create a JAXBContext using the newInstance method. Like this:
    JAXBContext.newInstance("com.myapp.myschema.packagename");This worked fine with JAXB1.0, but now I get the following stacktrace. I suspect that this error occurs due to som package problems, but I have no idea how to fix it. Can anyone help me??
    Heres the stacktrace:
    java.lang.InternalError
         at com.sun.xml.bind.v2.model.annotation.RuntimeInlineAnnotationReader.getClassValue(RuntimeInlineAnnotationReader.java:99)
         at com.sun.xml.bind.v2.model.annotation.RuntimeInlineAnnotationReader.getClassValue(RuntimeInlineAnnotationReader.java:17)
         at com.sun.xml.bind.v2.model.core.Adapter.<init>(Adapter.java:43)
         at com.sun.xml.bind.v2.model.impl.PropertyInfoImpl.<init>(PropertyInfoImpl.java:88)
         at com.sun.xml.bind.v2.model.impl.SingleTypePropertyInfoImpl.<init>(SingleTypePropertyInfoImpl.java:35)
         at com.sun.xml.bind.v2.model.impl.AttributePropertyInfoImpl.<init>(AttributePropertyInfoImpl.java:23)
         at com.sun.xml.bind.v2.model.impl.RuntimeAttributePropertyInfoImpl.<init>(RuntimeAttributePropertyInfoImpl.java:18)
         at com.sun.xml.bind.v2.model.impl.RuntimeClassInfoImpl.createAttributeProperty(RuntimeClassInfoImpl.java:68)
         at com.sun.xml.bind.v2.model.impl.ClassInfoImpl.addProperty(ClassInfoImpl.java:747)
         at com.sun.xml.bind.v2.model.impl.ClassInfoImpl.getProperties(ClassInfoImpl.java:257)
         at com.sun.xml.bind.v2.model.impl.RuntimeClassInfoImpl.getProperties(RuntimeClassInfoImpl.java:89)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:127)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:49)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:41)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:189)
         at com.sun.xml.bind.v2.model.impl.TypeRefImpl.calcRef(TypeRefImpl.java:56)
         at com.sun.xml.bind.v2.model.impl.TypeRefImpl.getTarget(TypeRefImpl.java:33)
         at com.sun.xml.bind.v2.model.impl.RuntimeTypeRefImpl.getTarget(RuntimeTypeRefImpl.java:22)
         at com.sun.xml.bind.v2.model.impl.RuntimeTypeRefImpl.getTarget(RuntimeTypeRefImpl.java:15)
         at com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.get(ElementPropertyInfoImpl.java:38)
         at com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.get(ElementPropertyInfoImpl.java:41)
         at java.util.AbstractList$Itr.next(AbstractList.java:422)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:139)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:49)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:41)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:189)
         at com.sun.xml.bind.v2.model.impl.TypeRefImpl.calcRef(TypeRefImpl.java:56)
         at com.sun.xml.bind.v2.model.impl.TypeRefImpl.getTarget(TypeRefImpl.java:33)
         at com.sun.xml.bind.v2.model.impl.RuntimeTypeRefImpl.getTarget(RuntimeTypeRefImpl.java:22)
         at com.sun.xml.bind.v2.model.impl.RuntimeTypeRefImpl.getTarget(RuntimeTypeRefImpl.java:15)
         at com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.get(ElementPropertyInfoImpl.java:38)
         at com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.get(ElementPropertyInfoImpl.java:41)
         at java.util.AbstractList$Itr.next(AbstractList.java:422)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:139)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:49)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:41)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:189)
         at com.sun.xml.bind.v2.model.impl.RegistryInfoImpl.<init>(RegistryInfoImpl.java:63)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.addRegistry(ModelBuilder.java:232)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:201)
         at com.sun.xml.bind.v2.runtime.JAXBContextImpl$3.run(JAXBContextImpl.java:352)
         at com.sun.xml.bind.v2.runtime.JAXBContextImpl$3.run(JAXBContextImpl.java:350)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:349)
         at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:215)
         at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:76)
         at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:55)
         at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:124)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:132)
         at javax.xml.bind.ContextFinder.find(ContextFinder.java:286)
         at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:372)
         at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:337)
         at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:244)

    I did have the same problem and it took me several hours to figure it out. Here is what I did, it might be useful for others later.
    I have a number of opened projects and needed to reference them in my ant build.xml
    The program runs fine from eclipse, but dies when I run the created jar file from command line.
    The line of code where it stopped was
    JAXBContext context = JAXBContext.newInstance(jaxbPackage);
    with the above InternalError printstack printed. Which was not really informative.
    Apparently, one of the referenced projects indirectly required other projects which I did not mention in my build.xml It was obviously the packaging problem.
    You can also check the version of you jvm in your terminal and in your eclipse; check the class path in eclipse and temporarily add all the missing lines to your CLASSPATH. If the problem goes away, you can easily figure out which class path was missing.

Maybe you are looking for