Constructors invocation

Hello,
Here is a problem I've experienced: The constructor of the abstract class is calling the abstract createComponent() method that is implemented in the child class.
The child class can initialize the Component in the constructor. But, this constructor is executed after the abstract class constructor! So it does add(null) . What is the solution.
Here is the simpified code:
abstract class AbtractPanel extends JPanel
  AbstractPanel()
    add(createComponent());
  abstract protected void createComponent();
class MyPanel extends AbstractPanel
  JButton button;
  MyPanel(JButton b)
    button = b;
  protected void createComponent()
    return button;
  }

Hello,
Here is a problem I've experienced: The constructor of
the abstract class is calling the abstract
createComponent() method that is implemented in the
child class.
The child class can initialize the Component in the
constructor. But, this constructor is executed
after the abstract class constructor! So it
does add(null) . What is the
solution.
Here is the simpified code:
abstract class AbtractPanel extends JPanel
AbstractPanel()
add(createComponent());
abstract protected void createComponent();
class MyPanel extends AbstractPanel
JButton button;
MyPanel(JButton b)
button = b;
protected void createComponent()
return button;
First of all the constructor AbstractPanel() will always be called FIRST from ANY of its subclasses. Therefore the construction must take place in the createComponent method NOT the MyPanel constructor. For instance
MyPanel(JButton b)
   super();
button = b;
}Note the call super() which is the first thing called by the MyPanel constructor. This is done automatically by java and you can NOT stop it. This call equates to calling the AbstractPanel() constructor which in turn calls the createComponent() method of MyPanel. This all takes place BEFORE button = b; So when createComponent is called, button == null.
The basic way to solve this is to add another constructor to the AbstractPanel class
abstract class AbtractPanel extends JPanel
AbstractPanel()
add(createComponent());
AbstractPanel(JButton b)
  add(b);
abstract protected void createComponent();
class MyPanel extends AbstractPanel
JButton button;
MyPanel(JButton b)
super(b);
}There are actually other ways to solve this if I knew your objective.

Similar Messages

  • Recursive constructor invocation ?

    heya all
    i can seam to grasp how to correct this error anyone help ?
    public class Shop
        public static void main(String args[])
            Book book1, book2, book3;
            Pen pen1, pen2;
            book1 = new Book("Pigs may fly", 100, 120);
            book2 = new Book("Pigs can't fly", 75, 100);
            book3 = new Book ("Pigs must not fly", 10, 75, 100);
            pen1 = new Pen("Balck", 10, 10, 15);
            pen2 = new Pen("Blue", 10, 15);
            book1.purchaseCopies(10);
            book2.purchaseCopies(10);
            pen2.purchasePens(10);
            book1.sellCopies(5);
            book2.sellCopies(2);
            book3.sellCopies(1);
            pen1.sellPens(10);
            pen2.sellPens(3);
            System.out.println("\nBooks");
            book1.printDetails();
            book2.printDetails();
            book3.printDetails();
            System.out.println("\nPens");
            pen1.printDetails();
            pen2.printDetails();
            System.out.print("\nTotal profit");
            int sum = book1.calculateProfit();
            sum += book2.calculateProfit();
            sum += book3.calculateProfit();
            sum += pen1.calculateProfit();
            sum += pen2.calculateProfit();
            System.out.println(sum + "p");
    public class Pen
        private String inkColour;
        private int numPensPurchased;
        private int purchasePricePerPen;
        private int salePricePerPen;
        private int numPensSold;
        public Pen(String ink, int purchasePrice, int salePrice)
        this (ink, 0, purchasePrice, salePrice);
        public Pen(String ink, int numPens, int purchasePrice, int salePrice)
            inkColour = ink;
            numPensPurchased = numPens;
            purchasePricePerPen = purchasePrice;
            salePricePerPen = salePrice;
            numPensSold = 0;
        public void purchasePens(int numPens)
            numPensPurchased += numPens;
        public void sellPens(int numPens)
            numPensSold += numPens;
        public int calculateProfit()
            return numPensSold* (salePricePerPen - purchasePricePerPen);
        public void printDetails()
        System.out.printf("%8s; %3d bought @ %3dp; %3d Sold @ %3dp; profit is %5dp",
                inkColour,
                numPensPurchased, purchasePricePerPen,
                numPensSold, salePricePerPen, calculateProfit());
    public class Book
        private String title;
        private int numCopiesPurchased;
        private int purchasePricePerCopy;
        private int salePricePerCopy;
        private int numCopiesSold;
        public Book(String theTitle, int purchasePrice, int salePrice)
        this(theTitle, purchasePrice, salePrice);
        public Book(String theTitle, int numCopies, int purchasePrice, int salePrice)
        title = theTitle;
        numCopiesPurchased = numCopies;
        purchasePricePerCopy = purchasePrice;
        salePricePerCopy = salePrice;
        numCopiesSold = 0;
        public void purchaseCopies(int numCopies)
        numCopiesPurchased += numCopies;
        public void sellCopies(int numCopies)
        salePricePerCopy += numCopies;
        public int calculateProfit()
        return numCopiesSold*(salePricePerCopy - purchasePricePerCopy);
        public void printDetails()
        System.out.printf("%8s; %3d bought @ %3dp; %3d Sold @ %3dp; profit is %5dp",
                title,
                numCopiesPurchased, purchasePricePerCopy,
                numCopiesSold, salePricePerCopy, calculateProfit());
    }I found this example of how to solve it , but i cant seam to adapt if for this ?
    public Rectangle( float L, float W ) {
    this( L, W );
    }should be changed to..
    public Rectangle( float L, float W ) {
    setLength(L);
    setWidth(W);
    }

    You have the same problem with this:
    public Book(String theTitle, int purchasePrice, int salePrice)
        this(theTitle, purchasePrice, salePrice);
        }Just keeps calling itself. Fix that
    That is the one im trying to fix
    the other one is an example but if i try to put
    settitle (theTitle);
    setpurchasePricePerCopy (purchasePrice);
    setsalePricePerCopy (salePrice);
    }it dosnt work ?
    Edited by: Javaman01 on Aug 19, 2009 12:33 AM

  • How to find out which class invoked the constructor

    i wrote a class named DAOBase and i am creating object of the same in several other classes. So is there any way to know which class has invoked the constructor of DAOBase.
    i want to print out the name of the class that invoked the constructor of DAOBase at the time of constructor invocation...
    Is there any way?
    Please Help...

    Alternatively, use SecurityManager.getClassContext() as inclass CallerAndMain {
         public static void main(java.lang.String[] args) {
              System.out.println("I'm in " + new SecurityManager() { public String getClassName() { return getClassContext()[1].getName(); } }.getClassName() + " class");
              new Try();
    class Try {
         public Try() {
              System.out.println("I'm in " + new SecurityManager() { public String getClassName() { return getClassContext()[1].getName(); } }.getClassName() + " class");
              System.out.println("I was called from " + new SecurityManager() { public String getClassName() { return getClassContext()[2].getName(); } }.getClassName() + " class");
    }

  • JMS Adapter: Error executing MQQueueConnectionFactory constructor

    Hello exerts,
    My Sender JMS Comm. Channel is throwing class not found error for com.ibm.mq.jms.MQQueueConnectionFactory. I set my JMS adapter logging level to DEBUG and this is what I got. It is crashing on Constructor. Doesn't anyone have any idea what might be wrong. We have an App server sitting in from on our PI box and they both have same jms libraries on them.
    Thanks, Mayur
    Caught com.sap.aii.adapter.jms.api.base.ConstructorInvocationException: Error executing constructor invocation:
    {ConstructorInvocation
    {className=com.ibm.mq.jms.MQQueueConnectionFactory,
    invokeParams=[]
    }: SAPClassNotFoundException: com.ibm.mq.jms.MQQueueConnectionFactory
    at com.sap.aii.adapter.jms.core.common.InvokeUtils.invoke(InvokeUtils.java:284)

    Hello Experts, just wanted to post an update of this issues. We were able to fix our issues by wipeing out all existing JMS libraries in our PI 7.1 environement and redeploying a fresh library (com.sap.aii.adapter.lib.sda).
    Currently this library contain following JAR files.
    lib/com.ibm.mq.jar
    lib/com.imb.mqjms.jar
    lib/connector.jar
    lib/dhbcore.jar
    lib/com.sap.aii.adapter.lib_api.jar
    Thanks,
    Mayur

  • Bypassing Constructors....

    Hi there,
    Does anyone know how to create a new instance without causing invocation of a constructor? Its driving me mad - I know I've got it in one of my reference books (Java XML I think, where they create custom XML serialization streams) - but I cant find it!
    Ive got a feeling it might be in one of the sun.misc classes....
    Does anyone know....?

    Why do you want to do that? Cos Im a monkey :o)
    Apart from that, Im knocking up a rules engine for creating fully populated class instances for as many class types in my application that I can get it to manage. In certain scenarios the ability to do this comes in handy for me.
    and I don't see a reason to do itObject creation without constructor invocation is also used for standard (java.io) Object de-serialization. I can imagine it being equally useful in other object persistence frameworks too.

  • What is an empty constructor?

    Hi.
    This might be a dumb question but I need to know what is an empty constructor?
    I've checked my Murach and there is nothing mentioned.
    Thank you.

    jverd wrote:
    In fact, I'm pretty sure the compiler puts the bytecodes for a super(); call into your class file just as if you had explicitly written it in the constructor body.Yes that is what the Sun compiler does.
    I was also curious what exactly what the specification says about what it should do.
    If it is required to do the code insertion then there should be a verification rule. I certainly couldn't find one.
    I did find the following in both the JLS and the VM Spec in the "Creation of New Class Instances" sections.
    +"This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or _implicit_ invocation of a superclass constructor (using super). "+
    That would suggest that a compiler is free to leave it out and then the VM would be responsible for calling the parents ctor. It doesn't even say which ctor it must call in that case, so presumably the VM could use a best match algorithm based on the current ctors parameters.

  • Using this with a Constructor??

    What is explicit constructor invocation?
    I can't really understand this. I've been reading this for many times but my dull head does not really understand..Please help..!!

    http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.8.7.1

  • Why are Constructor not inherited?

    Hello,
    how come Java Constructors are not inherited by subclasses? Consider:
    ClassA
    ClassA(someParameters)
    ClassB extends ClassA
    How come do I need to declare a Constructor in ClassB that will accept "someParameters"? Why don't my ClassB simply inherites its parent Constructor?
    Thanks for any insights :-)
    PA.

    Hi,
    Straight from the Java Language Specs:
    2.12 Constructors
    A constructor is used in the creation of an object that is an instance of a class. The constructor declaration looks like a method declaration that has no result type. Constructors are invoked by class instance creation expressions, by the conversions and concatenations caused by the string concatenation operator +, and by explicit constructor invocations from other constructors; they are never invoked by method invocation expressions.
    Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.
    If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of the direct superclass that takes no arguments.
    If a class declares no constructors then a default constructor, which takes no arguments, is automatically provided. If the class being declared is Object, then the default constructor has an empty body. Otherwise, the default constructor takes no arguments and simply invokes the superclass constructor with no arguments. If the class is declared public, then the default constructor is implicitly given the access modifier public. Otherwise, the default constructor has the default access implied by no access modifier.
    A class can be designed to prevent code outside the class declaration from creating instances of the class by declaring at least one constructor, in order to prevent the creation of an implicit constructor, and declaring all constructors to be private.
    This should answer your question and then some.
    Try reading the JLS yourself to get answers as to why ... then come back here and get help with how.
    http://java.sun.com/docs/books/vmspec/2nd-edition/html/VMSpecTOC.doc.html
    Regards,
    Manfred.

  • ClassNotFoundException for a single class in my project... HELP!

    Hey all,
    I hope someone has an answer to my problem because I wasted enough time trying to figure it myself and, admittedly, I have no idea what I'm doing.
    So I have two projects in Eclipse. One project contains a bunch of data access objects (DAO) -- my data access layer -- and the other project is a tool which uses the DAOs to perform some operations. So everything was going hunky-dory until I made an instance of this one DAO class in my tool. When I tried running it, I got a ClassNotFoundException being thrown from the constructor invocation (i.e., new DAO()). It didn't execute the constructor, it just went straight into the exception code. This makes no sense to me because every other DAO class I'm using in my tool works just fine.
    I've tried cleaning my projects out and rebuilding to no avail. I've also deleted them from my workspace and checked them out from my CVS server, again to no avail. Does anyone know why this one DAO is not visible to my tool?! Why it can't find it?!
    I'm willing to try anyone's suggestion at this point, so please help! I'd appreciate it. Thanks!

    This makes no sense to meWhat you are dealing with here is a classpath issue. At compile time, apparently whatever DAO class you need is available and the compiler has nothing to complain. When the application is executed however, the DAO class is no longer in the classpath.
    So how is your DAO project built? If it is a jar (if it is not, it should be), then that jar is not in the classpath of your tool while it is being executed. Most likely you need to add the jar as a library to the project of your tool for it to work.

  • Big Big Funky Question

    Hey people,
    This might be a stupid question but I'm just wondering what variables in java are initialized to if they are even initialized. Are they initialized and to what? The data types I'm talking about are int,boolean,String,byte,char which are the ones I deal with most.

    Variables don't have default values. Fields do.I thought I held the "Pedant of the Day"? award,
    but I see that I've been usurped... ;o)We must revoke the archivist's award.
    "[JLS section]4.5.3 Kinds of Variables
    There are seven kinds of variables:
    1. A class variable is a field declared using the keyword static within a class declaration (�8.3.1.1), or with or without the keyword static within an interface declaration (�9.3). A class variable is created when its class or interface is prepared (�12.3.2) and is initialized to a default value (�4.5.5). The class variable effectively ceases to exist when its class or interface is unloaded (�12.7).
    2. An instance variable is a field declared within a class declaration without using the keyword static (�8.3.1.1). If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value (�4.5.5) as part of each newly created object of class T or of any class that is a subclass of T (�8.1.3). The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object (�12.6) has been completed.
    3. Array components are unnamed variables that are created and initialized to default values (�4.5.5) whenever a new object that is an array is created (�15.10). The array components effectively cease to exist when the array is no longer referenced. See �10 for a description of arrays.
    4. Method parameters (�8.4.1) name argument values passed to a method. For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked (�15.12). The new variable is initialized with the corresponding argument value from the method invocation. The method parameter effectively ceases to exist when the execution of the body of the method is complete.
    5. Constructor parameters (�8.8.1) name argument values passed to a constructor. For every parameter declared in a constructor declaration, a new parameter variable is created each time a class instance creation expression (�15.9) or explicit constructor invocation (�8.8.5) invokes that constructor. The new variable is initialized with the corresponding argument value from the creation expression or constructor invocation. The constructor parameter effectively ceases to exist when the execution of the body of the constructor is complete.
    6. An exception-handler parameter is created each time an exception is caught by a catch clause of a try statement (�14.19). The new variable is initialized with the actual object associated with the exception (�11.3, �14.17). The exception-handler parameter effectively ceases to exist when execution of the block associated with the catch clause is complete.
    7. Local variables are declared by local variable declaration statements (�14.4). Whenever the flow of control enters a block (�14.2) or for statement (�14.13), a new variable is created for each local variable declared in a local variable declaration statement immediately contained within that block or for statement. A local variable declaration statement may contain an expression which initializes the variable. The local variable with an initializing expression is not initialized, however, until the local variable declaration statement that declares it is executed. (The rules of definite assignment (�16) prevent the value of a local variable from being used before it has been initialized or otherwise assigned a value.) The local variable effectively ceases to exist when the execution of the block or for statement is complete."

  • Swing Programming Question

    Hi, and thanks for reading this.
    I have a simple Swing application. When launching the application, it displays a "JFrame" that contains a "JButton". When activating the "JButton", a custom "JDialog" is opened. The custom "JDialog" is a class that I wrote that extends "JDialog". The constructor for this custom "JDialog" builds the dialog and displays it. Currently, the "actionPerformed()" method (of the "JButton", in the "JFrame") invokes the custom "JDialog"'s constructor (no, not every time, but the constructor has to be called sometime, right?). My question is, should the constructor invocation be wrapped in a "SwingUtilities.invokeLater()" or "SwingUtilities.invokeAndWait()", or not?
    Thanks (in advance),
    Avi.

    It's not necessary. actionPerformed() is invoked by the event dispatch thread in reaction to a mouse event, so it's safe for any gui manipulation code to be placed in that method.

  • Is there a final specification of Java generics?

    The longer I look into the draft specification the more mysterious it looks to me. This cannot be the final specification of a new language feature. Does anybody know where the feature is actually specified?
    Just as an example: page 13 of the draft spec (dated April 27, 2001) says:
    Given the method declarations:
    static <A> Seq<A> nil() { return new Seq<A>(); }
    static <A> Seq<A> cons(A x, Seq<A> xs)
    { return new Seq<A>(x, xs); }
    The following is a legal expression:
    cons(new IOException(), cons(new Error(), nil())) // of type: Seq<Throwable>
    The generics compiler, however, rejects it saying:      
    cons<A>(A,Seq<A>) cannot be applied to (IOException,Seq<Error>)
    Frankly said, I think, the compiler is right and the draft specification is wrong. Seemingly the idea of type parameter inference is that each actual argument type is a subtype of the corresponding formal argument type that was found by means of type parameter inference.
    In the example above, if type Throwable were deduced for the type variable A, then the first formal method argument were of type Throwable and the actual argument would be of a subtype, namely IOException. Fine. But the second formal method argument would then be Seq<Throwable> and the actual argument is a Seq<Error>, which is not a subtype of Seq<Throwable>. I think, there is no parameter inference possible that makes sense for this example. Hence the compiler rightly rejects it.
    I guess, obvious mistakes like this have long been fixed in the specification. Where is the most recent release of the spec? I could not find anything on Sun's website.

    Just to be more helpful, my corrected grammar for MethodInvocation is:
    MethodInvocation ::= MethodExpr ( ArgumentListOpt )
    MethodExpr     ::= MethodName
               |  Primary . TypeArgumentsOpt Identifier
               |  super . TypeArgumentsOpt Identifier
               |  Name . super . TypeArgumentsOpt Identifierwhile the original grammar contained this production:
    MethodExpr     ::= TypeArgumentsOpt MethodName
                     |  ...Type arguments in front of an unqualified method name can't be unambiguously parsed, so they have been made illegal. You need to use a primary (a class expression for non-static methods or a class name for static methods) to resolve the ambiguity.
    Similarly, the corrected constructor invocation productions are:
    ClassInstanceCreationExpression ::= new TypeArgumentsOpt
         ClassOrInterfaceType ( ArgumentListOpt ) ClassBodyOpt
                         |  Primary . new TypeArgumentsOpt
         Identifier TypeArgumentsOpt ( ArgumentListOpt ) ClassBodyOptwhile the original was:
    ClassInstanceCreationExpression ::= TypeArgumentsOpt new
                         ClassOrInterfaceType TypeArgumentsOpt
                                                ( ArgumentListOpt ) ClassBodyOpt
                                        |  Primary.TypeArgumentsOpt new
                         Identifier TypeArgumentsOpt
                                                ( ArgumentListOpt ) ClassBodyOpthere the placement of the TypeArguments productions had to be moved in order to resolve grammar ambiguities; in addition "ClassOrInterfaceType" already includes an optional final TypeArguments clause, and so the extra one in the first alternative needed to be removed.

  • Construction (just out of interest)

    After puzzling over this for some time I have concluded that construction must occur sort of in this order:
    memory allocated
    super called
    variables initialised
    constructor body called.
    however after seeing some results I am rather confused. From the following code sample (without arguing whether the code is 'correct') the results have confused me:
    abstract class A {
       C c = new C();
        public A() {
           configure();
           System.out.println("A.A()");
        public abstract void configure();
    public class B extends A {
       String myVar = "INIT";
       public B() {
         super();
         System.out.println("B.B()");
       public void configure() {
        System.out.println("B.configure()");
          myVar = "FOO";
    public static void main(String[] args){
         B b = new B();
         System.out.println("myVar: " + b.myVar);
    class C{
    C(){
      System.out.println("C.C()");
    }printing out
    C.C()
    B.configure()
    A.A()
    B.B()
    myVar: INITso we can assume that when the constructor of B is first entered myVar is already set to "INIT", configure then sets it to "FOO", but when the super constructor exits myVar is reset to "INIT" which seems to suggest that the variable is initialised twice.. giving us an order of:
    memory allocated
    variables initialised
    super called
    variables initialised
    constructor body called.
    Is this correct? And is there a reason for it being done like this? couldn't the JVM just get away with doing?
    memory allocated
    variables initialised
    super called
    constructor body called.
    these results have been observed in 1.4.1_02, is this likely to be different in different JVM's?
    Thanks for your time

    This is what happens:
    Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden. If there is not sufficient space available to allocate memory for the object, then creation of the class instance completes abruptly with an OutOfMemoryError. Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values.
    Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:
    # Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.
    # If this constructor begins with an explicit constructor invocation of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 5.
    # If this constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this) and is in a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.
    # Execute the instance variable initializers for this class, assigning their values to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5. (In some early implementations, the compiler incorrectly omitted the code to initialize a field if the field initializer expression was a constant expression whose value was equal to the default initialization value for its type. This was a bug.)
    # Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

  • Identifying Class ?

    Hi,
    my problem is the following:
    To get the parameter type of a constructor I use constructor.getParameterTypes() which returns a Class<?> array. Now I want to look at each of the parameter classes and do something, depending on the type. I know that the type is int, double, or boolean.
    I could do this:
    public void foo(Class<?> c){
       if (c == int.class){
       else if (c == double.class){
       else if (c == boolean.class){
    }But of course conditional logic is totally uncool. ;-)
    Is there any better way to do it (something like polymorphism)?
    Thanks
    Frank

    Reflection code tends to be either beautiful code or downright ugly.
    In this case you may have to settle for the ugly approach however there are things you can do to make things a little easier.
    1- Code a set of classes that can be used as value converters. You also need an abstract class for these classes that exposes methods for accepting parameters of the type you wish to convert from which returns a converted value as an Object (which is what you want for your parameter list for Method or Constructor invocations).
    This abstract class should also act as a Factory for instances of the converters, the actual instance returned is determined by a Class parameter to the producer method.
    Example..
    * The example shows how to provide an interface for converting primitive and String values to the required
    * parameter type and value of that type.
    * The abstract class exposes methods that are overloaded for each type you want to convert, the methods
    * return Objects whose actual type is determined by the implementation classes, here as private nested
    * classes
    * It should be obvious enough to extend to suit your needs
    public abstract class ValueConverter {
      private static HashMap converters = new HashMap();
      //** It would be more efficient to use a single IntegerConverter for both int and Integer, CBA to do that here
      static {
        converters.put( Integer.TYPE, new IntegerConverter() );
        converters.put( Integer.class, new IntegerConverter() );
       * Returns a ValueConverter implementation that is suitable for
      public static ValueConverter getConverterInstance( Class parameterClass ) {
        return (ValueConverter)converters.get( parameterClass );
      //** For brevity I am confining the conversion methods to int and String types
      public abstract Object convert( int param );
      public abstract Object convert( String param );
      private static class IntegerConverter extends ValueConverter {
        IntegerConverter() {
        public Object convert( int param ) {
          return new Integer( param );
        public Object convert( String param ) {
          try {
            return new Integer( param );
          } catch( NumberFormatException e ) {
            throw IllegalArgumentException( "Not able to parse argument to an Integer:" + param );
    }And here is how use the above code
      //** Assume you already have the paramter array for your Constructor, obtained by reflection
      //** Class[] paramTypes...
      Object[] params = new Object[paramTypes.length ];
      for( int i = 0; i < paramTypes.length; i++ ) {
        Class paramType = paramTypes;
    ValueConverter converter = ValueConverter.getConverterInstance( paramType );
    params[i] = converter.convert( "1" ); //** For instance
    //** Using the params array you can now invoke the constructor
    If I got things right you should be able to see how you can extend the converter solution to meet your needs
    and avoid the ugly if..else if..else if.. code.

  • Inner/Outer classes - curious matter

    Hi,
    This is from Sun Certified Programmer practice exam:
    class Outer {
       class Inner {}
    class ExtendedOuter extends Outer {
       class ExtendedInner extends Inner {}
    class Main extends Outer.Inner {
       Main( Outer ref ) {
            ref.super();
       public static void main( String[] args ) {
            new Main( new ExtendedOuter() );
    }The choices are:
    A) Compilation fails
    B) An exception is thrown at runtime
    C) The code runs with no output
    My answer was A because the line ref.super() doesn't make sense to me.
    But the correct answer is C.
    As far I as knew - super is a keyword and can be used either to access hidden members of the superclass, or to invoke specific constructor from the superclass also. What is it here???
    Could somebody explain what this line does?

    Is that because class files with no declared package
    location are automatically placed in the same
    package?Classes with no declared package are all part of an unnamed package, commonly referred to as the default package.
    In general, you should always use packages, as support for unnamed packages is implementation dependent (although all compilers and JVMs must support an unnamed package). Depending on the platform you are using, the unnamed package might include all directories and jar files on your classpath, just the current working directory, just the first directory on your classpath, or something else.
    But `ref' is not an instance of Main, but is an
    instance of ExtendedOuter (whose superclass is
    Object). Actually ExtendedOuter's superclass is Outer. However all that is important is that it is an instance of Outer, since the type checking is performed at compile time.
    So how can it be calling Main's?Because it is a superclass constructor invocation in class Main. Therefore it calls a constructor in Main's superclass. This is the syntax used to call a superclass constructor where the superclass is an inner class and the enclosing instance needs to be specified. ref is the object to be used as the enclosing instance - there is no clever trick to it - it is just a syntax.
    Also, if an instance of an innerclass exists, than an
    instance of it's outerclass must also exist. Yes, in the example the outer class instance is ref.
    Then
    won't calling the constructor of a superclass (with
    `ref.super()') be calling the constructor again after
    it (the superclass) has already existed?You can not create an object (other than instances of java.lang.Object) without calling a superclass constructor.

Maybe you are looking for

  • My Mac is exceptionally slow, what can I do?

    Ok, heres the story. The day after christmas 2012, December 26 2012, I upgraded my Macbook Pro from Snow Leopard to Mountain Lion. I originally got the mac in 2010. The upgrade went by fine but after I noticed that the mac was slower than before, it

  • How to add new line item using BAPI BAPI_CONTRACT_CHANGE for contract-ME32K

    HI Experts, how to add new line item using BAPI: BAPI_CONTRACT_CHANGE for existing contract. Requirement: Already the contract having two line items using ME31K. Custom program has to add new line items in existing contract. Thanks, Sendil

  • How to validate date columns in tabular forms?

    Hi, I have two date columns in a tabular form 1.Start_date 2.End_date so here i need to validate the end_date as should not be lesser value than start_date column so any solution for this?

  • IDM: Implementing Password Synchronization only

    Hello to everyone. We are currently implementing IDM (7.2) by phases. For the first phase, we are planing to cover u201Cpaswword synchronizationu201D only. Therefore we are going to continue administrating user accounts in a descentralized way (Activ

  • Payables data stuck in gl_interface table

    Created Invoices in Payables. Validated process run for create accounting & trasfer to gl resulted in warning with message in log: SHRD0008: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ R_CLPR0003: Unprocessed records exist i