Create an object instance without calling its constructor?

Hi,
Sometimes it's useful to create object instances without calling their constructor. When? For example object deserialization.
By default when deserializating an object, the instance in the VM is created by calling the default constructor of the first non Serializable super-class (if you don't have such you're in trouble). I think that the db4o object database don't even call any constructor you may have written.
So such thing exists, but how is this possible? I fugured out that sun's deserialization mechanism first finds the constructor of the first non Serializable super-class and then:
cons = reflFactory.newConstructorForSerialization(cl, cons); Here I'm stuck.
Here's the source of the method for finding serializable constructor:
     * Returns subclass-accessible no-arg constructor of first non-serializable
     * superclass, or null if none found.  Access checks are disabled on the
     * returned constructor (if any).
    private static Constructor getSerializableConstructor(Class cl) {
     Class initCl = cl;
     while (Serializable.class.isAssignableFrom(initCl)) {
         if ((initCl = initCl.getSuperclass()) == null) {
          return null;
     try {
         Constructor cons = initCl.getDeclaredConstructor(new Class[0]);
         int mods = cons.getModifiers();
         if ((mods & Modifier.PRIVATE) != 0 ||
          ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
           !packageEquals(cl, initCl)))
          return null;
         cons = reflFactory.newConstructorForSerialization(cl, cons);
         cons.setAccessible(true);
         return cons;
     } catch (NoSuchMethodException ex) {
         return null;
    }So any info about this ReflectionFactory, and the problem as a whole?
Thanks.

So the question is how to create object instance without initializing it (calling the constructor)? And if you have any info about ReflectionFactory it will be useful too.
When serializing an object you save all its fields and some extra info. When you deserialize it you have to reconstruct it, by copying the fields back, but not to reinitialize.
import java.lang.reflect.*;
import java.io.Serializable;
import java.security.AccessController;
import sun.reflect.ReflectionFactory;
public class Test0 implements Serializable {
    public Test0() {
        System.out.println("Test0");
    public static void main(String[] args) throws Exception {
        Constructor<Test0> constr = reflectionFactory.newConstructorForSerialization(Test0.class, Object.class.getConstructor(new Class[0]));
        System.out.println(constr.newInstance(new Object[0]).getClass());
    private static final ReflectionFactory reflectionFactory = (ReflectionFactory)
     AccessController.doPrivileged(
         new ReflectionFactory.GetReflectionFactoryAction());
}When you execute this piece you get:
class Test0

Similar Messages

  • Always create any Object even without default constructor?

    hi!
    i'm wondering if there's an easy way to construct an object of a given class?
    let's assume i've got a class
    class MyClass
         public MyClass( OtherClass c)
    }now when i get the constructors for its Class-object with
    clazz.getDeclaredConstructor()
    it will return null;
    ok now i know ther's no default/empty constructor.
    does it make sense to then search for the next constructor with n parameters?
    and then invoke it with nonsense values?
    what happens if the parameter classes also have no default constructor to create parameter objects? like this:
    class OtherClass
         public OtherClass ( MyClass c)
    }now there's a loop between the two constructors and i can't create empty parameter values to invoke any of them!
    i wonder how the serialization engine works then?
    or did i miss something trivial (it's really late here ;) )

    What's the problem? To create a MyClass object, you
    don't need any OtherClass objects. You just do the
    equivalent ofnew MyClass(null)in your
    reflective code.
    slap forehead with toilet
    thanks for the tip.
    as i said there was something absolutely easy, it's tough not seeing the forest for the trees ;/
    But I agree with jschell, if your requirements are to
    create objects of arbitrary classes and call
    arbitrary methods with arbitrary parameter lists,
    then whoever did your design didn't think for long
    enough.WELL. you're absolutely right. but when it's time to process ANY given object there's no reliability on whatever design was chosen. or, would you insist the developer had to provide standatized formats when you write a debugger? no it has to work with any. so must i!

  • Extending object, without calling super constructor

    public class Object1
        byte index;
        public Object1(byte i)
            index = i;
    public class Object2 extends Object1
        private byte j;
        public Object2() {
            super((byte) 0);
        public void setIndex(byte i)
            j = i;
    import java.util.*;
    public class Test1
        private ArrayList<Object1> aList;
        public Test1()
            aList = new ArrayList<Object1>();
        public void run()
            for (byte i = 0; i < 10; i++)
                aList.add(new Object1(i));
        public ArrayList<Object1> getResults()
            return aList;
    import java.util.*;
    public class Test2
        ArrayList<Object1> results;
         * Constructor for objects of class Test2
        public Test2()
            Test1 t1 = new Test1();
            t1.run();
            results = t1.getResults();
        public void run()
            Iterator<Object1> i = results.iterator();
            while (i.hasNext())
                Object2 o2 = (Object2) i.next();
    public class Test3
        public static void main(String[] args)
            Test2 t2 = new Test2();
            t2.run();
    }There are two things with this code that I'm having problems with.
    1. I want to create an object of class Object1 in Test1. That works fine. In Test2 I then want to extract the object from the ArrayList, but since Object2 extends Object1, I want to get an Object2 out from the ArrayList. However with the code above, I get a ClassCastException. If I leave out the cast, I get an incompatible types error.
    2. I want Object2 to be an extension of Object1, that is, with more fields and methods. But I have no need to create an object of class Object2, since I know I already have an ArrayList of Object1. So I want to remove the constructor from Object2, seeing as I won't need it. However, if I remove the super part (which, again, is not needed, as I will already have created my needed objects of class Object1 when I get there, and only need to EXTEND my Object1 objects), I get a cannot find symbol, constructor Object1() error.
    I'm not sure that I can solve problem 2 without using a super. But I am convinced that I must be able to get the Object1 objects out as Object2 instead. I would just like some help with how to do that.

    ThemePark wrote:
    But I am convinced that I must be able to get the Object1 objects out as Object2 instead. I would just like some help with how to do that.Maybe you don't understand how inheritance works. Go read a basic tutorial on inheritance. You can use an Object2 as an Object1, but not an Object1 as an Object2. You either have to create Object2 objects in the first place; or have to make a wrapper class that takes an Object1 and passes things to the Object1 object; and use objects of this wrapper class.

  • Create SOFM object instance from PDF

    Hi All,
    I am using 4.6 version of SAP where FM 'sap_wapi_attachment_add' is does not exit. My query is to create an attachment (SMARTFORM coverted in PDF) in ABAP progam which i have to send as attachment with a Decision Task in the workflow.
    I am able to send attachment with mail but to send attachment with decision task i need to create an instance of SOFM object. Please suggest an alternative method to do so instead of FM 'sap_wapi_attachment_add' .

    Hi Taran,
    I had put my code in workflow task. You can find the task method code below:
    *Data declaration
    DATA: GITAB     TYPE SOLIX_TAB,                     
          GSTAB     LIKE LINE OF GITAB,                 
          SOFM_KEY  TYPE SOFMK,                         
          GIT_LINES TYPE SOLI_TAB.                      
    DATA: LREF_DOCUMENT_BCS  TYPE REF TO CL_DOCUMENT_BCS,
          LREF_IM_DOCUMENT   TYPE REF TO IF_DOCUMENT_BCS.
    Generate Smartform*
    CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
        EXPORTING
          FORMNAME                 = C_FORM
    *      VARIANT                  = ' '
    *      DIRECT_CALL              = ' '
        IMPORTING
          FM_NAME                  = GV_FM
        EXCEPTIONS
          NO_FORM                  = 1
          NO_FUNCTION_MODULE       = 2
          OTHERS                   = 3.
      IF SY-SUBRC <> 0.
    *    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *       WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      CALL FUNCTION 'SSF_GET_DEVICE_TYPE'
        EXPORTING
          I_LANGUAGE                   = SY-LANGU
    *      I_APPLICATION                = 'SAPDEFAULT'
        IMPORTING
          E_DEVTYPE                    = GV_OUTPUT_OPTIONS-TDPRINTER
        EXCEPTIONS
          NO_LANGUAGE                  = 1
          LANGUAGE_NOT_INSTALLED       = 2
          NO_DEVTYPE_FOUND             = 3
          SYSTEM_ERROR                 = 4
          OTHERS                       = 5.
      IF SY-SUBRC <> 0.
    *    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *       WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      GV_OUTPUT_OPTIONS-TDNOPREV = 'X'.
      GV_CONTROL_PARAMETERS-GETOTF = 'X'.
      GV_CONTROL_PARAMETERS-NO_DIALOG = 'X'.
      CALL FUNCTION GV_FM
        EXPORTING
    *      ARCHIVE_INDEX              =
    *      ARCHIVE_INDEX_TAB          =
    *      ARCHIVE_PARAMETERS         =
          CONTROL_PARAMETERS         = GV_CONTROL_PARAMETERS
    *      MAIL_APPL_OBJ              =
    *      MAIL_RECIPIENT             =
    *      MAIL_SENDER                =
          OUTPUT_OPTIONS             = GV_OUTPUT_OPTIONS
          USER_SETTINGS              = 'X'
          GV_ENAME                   = GV_ENAME
          GV_PERNR                   = GV_PERNR
          GV_PERSK                   = GV_PERSK
          GV_ZZ_LEVEL                = GV_ZZ_LEVEL
          GV_BTRTX                   = GV_BTRTX
          GV_GBDAT                   = GV_GBDAT
          GV_JOIN_DATE               = GV_JOIN_DATE
          GV_RESIN_DATE              = GV_RESIN_DATE
        IMPORTING
          DOCUMENT_OUTPUT_INFO       = GV_DOCUMENT_OUTPUT_INFO
          JOB_OUTPUT_INFO            = GV_JOB_OUTPUT_INFO
          JOB_OUTPUT_OPTIONS         = GV_JOB_OUTPUT_OPTIONS
        EXCEPTIONS
          FORMATTING_ERROR           = 1
          INTERNAL_ERROR             = 2
          SEND_ERROR                 = 3
          USER_CANCELED              = 4
          OTHERS                     = 5.
      IF SY-SUBRC <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      CALL FUNCTION 'CONVERT_OTF_2_PDF'
    *    EXPORTING
    *      USE_OTF_MC_CMD               = 'X'
    *      ARCHIVE_INDEX                =
        IMPORTING
          BIN_FILESIZE                 = GV_BIN_FILESIZE
        TABLES
          OTF                          = GV_JOB_OUTPUT_INFO-OTFDATA
          DOCTAB_ARCHIVE               = GIT_DOCS
          LINES                        = GIT_LINES_TEMP
        EXCEPTIONS
          ERR_CONV_NOT_POSSIBLE        = 1
          ERR_OTF_MC_NOENDMARKER       = 2
          OTHERS                       = 3.
      IF SY-SUBRC <> 0.
    *    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *       WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      CALL FUNCTION 'SX_TABLE_LINE_WIDTH_CHANGE'
        TABLES
          CONTENT_IN  = GIT_LINES_TEMP
          CONTENT_OUT = GIT_LINES.
      IF SY-SUBRC <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      CALL FUNCTION 'SO_SOLITAB_TO_SOLIXTAB'
        EXPORTING
          IP_SOLITAB  = GIT_LINES   "GIT_LINES_TEMP1
        IMPORTING
          EP_SOLIXTAB = GITAB.
    *Create SOFM object from smartform PDF
    IF NOT GITAB IS INITIAL.                    
          TRY.                                                        
              CALL METHOD CL_DOCUMENT_BCS=>CREATE_DOCUMENT            
                EXPORTING                                             
                  I_TYPE          = 'BIN'                             
                  I_SUBJECT       = 'NOTICE PAY WAIVER FORM'          
    *          I_LENGTH        =                                      
    *          I_LANGUAGE      = SPACE                                
    *          I_IMPORTANCE    =                                      
    *          I_SENSITIVITY   =                                      
    *          I_TEXT          =                                      
                  I_HEX           = GITAB                             
    *          I_HEADER        =                                      
    *          I_SENDER        =                                      
                RECEIVING                                             
                  RESULT          = LREF_DOCUMENT_BCS.                
            CATCH CX_DOCUMENT_BCS .                                   
          ENDTRY.                                                                               
    LREF_IM_DOCUMENT = LREF_DOCUMENT_BCS.                                                                               
    TRY.                                                        
              CALL METHOD LREF_DOCUMENT_BCS->ADD_DOCUMENT_AS_ATTACHMENT
                EXPORTING                                             
                  IM_DOCUMENT = LREF_IM_DOCUMENT.                     
            CATCH CX_DOCUMENT_BCS .                   
          ENDTRY.                                                                               
    TRY.                                        
              CALL METHOD LREF_DOCUMENT_BCS->GET_DOCTP
                RECEIVING                             
                  RESULT = SOFM_KEY-DOCTP.            
            CATCH CX_OS_OBJECT_NOT_FOUND .            
          ENDTRY.                                                                               
    TRY.                                        
              CALL METHOD LREF_DOCUMENT_BCS->GET_DOCYR
                RECEIVING                             
                  RESULT = SOFM_KEY-DOCYR.            
            CATCH CX_OS_OBJECT_NOT_FOUND .            
          ENDTRY.                                                                               
    TRY.                                        
              CALL METHOD LREF_DOCUMENT_BCS->GET_DOCNO
                RECEIVING                             
                  RESULT = SOFM_KEY-DOCNO.            
            CATCH CX_OS_OBJECT_NOT_FOUND .            
          ENDTRY.                                                                               
    SWC_CREATE_OBJECT NOTICE_PAY_WAIVER_FORM 'SOFM' SOFM_KEY.
          SWC_SET_ELEMENT CONTAINER 'NOTICE_PAY_WAIVER_FORM'      
                                     NOTICE_PAY_WAIVER_FORM.      
        ENDIF.
    The object instance thus created will be visible along with other  object instances in the workitem display. Provide this object in binding of decision step as you provise any other obect instance and not as ATTACH_OBJECT       
    Regards,
    Neha

  • Creating dynamic object instance names

    If I have a class such as ...
    class NewDevice
    I would create a new instance of that object by calling 'NewDevice' as ....
    NewDevice nd = new NewDevice();
    Suppose I don't actually know how many device I need before I read a file in and then subsequently create a new object instance. I could have a long list of variable name i.e. nd1, nd2, nd3 etc but that would be messy and I would be sure to run out.
    My Question..........
    How do I create object instances with unique names 'on-the-fly' so to speak
    Thanks

    Here's an example that allows you to build up a list of NewDevice instances, see how many there are and get them back by their index in the list:
    public class MyClass
      List newDeviceList;
      public MyClass()
        newDeviceList = new ArrayList();
      public void addNewDevice(NewDevice newDevice)
        newDeviceList.add(newDevice);
      public int getNewDeviceCount()
        return newDeviceList.size();
      public NewDevice getNewDevice(int idx)
        return (NewDevice)newDeviceList.get(idx);
    }Hope this helps.

  • Af:Table data refresh without calling ManagedBean constructor

    Hi,
    I have an adf application jspx page where I have af:selectOneChoice and af:table showing default data. On selecting af:selectOneChoice value (assigned, completed etc.) I am calling managed bean method which calls task flow client api which gets the task details based on af:selectOneChoice value and show in the adf table.
    When ever I change the af:selectOneChoice value, first it is callling 'valueChanged(ValueChangeEvent valueChangeEvent)' method in managed bean and able to get the records based on filter value(Example: Assigned). Issue is immediatly after that Managed bean constructor also calling which overrides the previous query and get the records based on default filter value (Example: All).
    here is <af:selectOneChoice & <af:table code:
    <af:selectOneChoice id="rsoc" autoSubmit="true"
    binding="#{backingBeanScope.backing_taskdetails.rsoc}"
    label="Status" valueChangeListener="#{backingBeanScope.backing_taskdetails.valueChanged}">
    <f:selectItem itemValue="A" itemLabel="All" />
    <f:selectItem itemValue="AG" itemLabel="Assigned" />
    <f:selectItem itemValue="C" itemLabel="Completed" />
    </af:selectOneChoice>
    <af:table emptyText="#{bindings.taskList.viewable ? 'No data to display.' : 'Access Denied.'}"
    var="row" columnStretching="multiple"
    value="#{backingBeanScope.backing_taskdetails.taskList}"
    immediate="false" rowSelection="single"
    binding="#{backingBeanScope.backing_taskdetails.t1}"
    id="t1"
    inlineStyle="font-family:Arial, Helvetica, sans-serif; border:0pt none; "
    partialTriggers="::rsoc">
    Here partialTriggers is invoking managed bean. So Can I refresh only table data without calling managed bean constructor on selection of <af:selectOneChoice?
    Any inputs will be highly appreciated. Thanks.

    Hi,
    Thanks for your reply.
    here it is my adfc-config.xml file.
    <?xml version="1.0" encoding="UTF-8" ?>
    <adfc-config xmlns="http://xmlns.oracle.com/adf/controller" version="1.2">
    <managed-bean id="__2">
    <managed-bean-name id="__3">backing_test</managed-bean-name>
    <managed-bean-class id="__4">view.backing.Test</managed-bean-class>
    <managed-bean-scope id="__1">backingBean</managed-bean-scope>
    <!--oracle-jdev-comment:managed-bean-jsp-link:1test.jspx-->
    </managed-bean>
    </adfc-config>
    I am not using adf taskflow (Should I use this, I am not sure as I am new to ADF. Please suggest). My execution flow is I have 'Human Task SOA application' which I am calling from adf application (managed bean --> workflow cllient API --> Human Task SOA Application) and showing task details in cutom UI screens. I do not want to use BPM worklist application as I need my own screens.
    thanks.

  • Why r we allowed to create String objects with & without using new operator

    While creating any object, usage of the new operator is a must...but only for the string object we can create it with and also without new operator how is it possible to create an object without using new operator.

    Because Mr. (Dr.?) Gosling is a kindly soul who realizes that programmers have deadlines and, when he designed Java, was not so rigid or unbending as not to realize that from time to time, certain shortcuts are warranted, even in a relatively pure language such as Java. The direct String literal assignments are a shortcut over using the new operator making Java programming (and execution; there's also a performance benefit) more streamlined.
    So look not the gift horse in the mouth, but simply bask in the simplification and ease on the eyes and directly assign your little literals to your heart's content.

  • How to create a new instance without XWindows in HP_U 8.1.7

    Can Somebody help me?
    I want to create a new instance in HP-UX 8.1.7 database. There is no Xwindows installed. I think i should do this in SQL plus.
    If so can sombody give my this script.
    thanks

    First get a Telnet session on your platform.
    In the following, foo is the name of the database to be created. Obviously you will replace this in your script names and script contents with the name of the database you are about to create.
    The values of parameters, filenames, distribution of files across filesystems, numbers and sizes of rollback segments and redo logs contained in these scripts should not be considered to be "recommended" in any way. These are just examples to demonstrate syntax. (Although the values given here will create a perfectly viable database.)
    create_db_foo.sql
    create database foo
    maxlogfiles 16
    maxlogmembers 3
    maxdatafiles 30
    maxinstances 1
    maxloghistory 100
    logfile
    group 1 (
    '/local/oracle/redo_logs/foo/log1a.rdo',
    '/local/oracle/redo_logs/foo/log1b.rdo'
    ) size 50M,
    group 2 (
    '/local/oracle/redo_logs/foo/log2a.rdo',
    '/local/oracle/redo_logs/foo/log2b.rdo'
    ) size 50M,
    group 3 (
    '/local/oracle/redo_logs/foo/log3a.rdo',
    '/local/oracle/redo_logs/foo/log3b.rdo'
    ) size 50M
    datafile
    '/local/oracle/data/foo/system.dbf' size 300m;
    create_ts_foo.sql
    create tablespace DATA
    datafile '/local/oracle/data/foo/data1.dbf' size 200m;
    create tablespace TEMP
    datafile '/local/oracle/data/foo/temp1.dbf' size 100m;
    create tablespace INDEXES
    datafile '/local/oracle/data/foo/indexes1.dbf' size 100m;
    create tablespace ROLLBACK_SEGS
    datafile '/local/oracle/data/foo/rbs.dbf' size 50m;
    create_rbs_foo.sql
    create rollback segment rbs_1
    tablespace rollback_segs
    storage (initial 1M next 1M
    minextents 5 maxextents unlimited
    create rollback segment rbs_2
    tablespace rollback_segs
    storage (initial 1M next 1M
    minextents 5 maxextents unlimited
    create rollback segment rbs_3
    tablespace rollback_segs
    storage (initial 1M next 1M
    minextents 5 maxextents unlimited
    create rollback segment rbs_4
    tablespace rollback_segs
    storage (initial 1M next 1M
    minextents 5 maxextents unlimited

  • Instance without calling 'new'

    I have a class that I use to extend MovieClip so I can add
    extra data to it. Along with other things I add a textField to the
    object when Instantiated. (I am including the basic class below) I
    have different movieClip symbols in the flash libray that I want to
    call when needed and add this functionallity to. The code works but
    I get an extra instance before I ever call 'new'. Flash seems to
    create an instance when run using the linkage properites 'base
    class' . I have to put my gamePiece class as the base class for the
    symbol in the library or it doesn't work. I'm really confused
    what's going on here. When I use in main() gamePiece:GamePiece =
    new redBall() it works fine (GamePiece is defined as the base class
    in the linkage properties for redBall. I hope I'm explaining this
    ok...Can anyone please tell me how I can keep Flash from creating
    an instance before I even use the class?
    Thanks

    oh, that is how I was told to do it. So I think I understand,
    so you can override the class that Flash creates automatically with
    the name used in the linkage properties for the symbol. So I create
    a gameBall1 class and extend GamePiece in there. Then for the base
    class in the linkage properties I use flash.display.MovieClip. Then
    to create it I would do this...
    var gp:GamePiece;
    gp = new gameBall1;
    Is that correct?
    Just so I have a better understanding of what was going on
    under the hood...the problem I was having is that flash was
    automatically creating an instance of the GamePiece class because
    it was listed in the symbol linkage properties as the base class?
    Thanks!

  • Can i CREATE Swing objects from without EDT?

    Subj
    Thenx.

    Yes, you can create Swing components and set their properties in any thread as long as the component hasn't been realized yet (by calling pack or setVisible on its parent).

  • A way to create new object instances in a loop?

    I have an square matrix of String values.
    Is there a way to take each row, make it into an object, and put the object in a new square matrix of objects?
    Any ideas?

    Do you mean something like this:Integer[][] foo = new Integer[5][5];
    for (int i = 0; i < foo.length; i++) {
        for (int j = 0; j < foo.length; j++) {
    foo[i][j] = new Integer(i + j);
    }It's hard to guess what you want, why not post some code (use the code tags: Formatting tips)

  • Reusing a variable from a new object instance

    I'm developing a stock list array for an assignment I'm currently working on. I've got most of it done, and it seems to be working for the most part, but I'm having trouble getting an array to accept individual variable entries created by new object instances in TestQ3.java.
    I think problem is because the variable itemCode in CraftItem.java is being overwritten by the creation of a new object instance in the TestQ3.java file. I've tested it and believe this to be true.
    I can add a String of my own choosing by using testArray.addCraftItemToStock(itemCode); line but I want to get the program to reuse the itemCode values that have already been created by the four new object instances in TestQ3.java. For example, I want to be able to add more instances of them to the testArray.
    As I'm still relatively new to Java programming, I'm wondering how to do this. I've tried several solutions but I'm not getting anywhere. I'd appreciate it if anyone has any ideas?
    Here's my code:
    TestQ3.java
    public class TestQ3 {
      public static void main(String args[]) {
        // creating a new StockItem array
        CraftStock testArray = new CraftStock(CraftStock.initialStockCapacity);
        // creating new object instance for Glue
        Glue gluePVA = new Glue("PVA Glue",250,"789012",2.50);
        // adds gluePVA item code to the testArray list
        // testArray.addCraftItemToStock(gluePVA.getItemCode());
        // creating new object instance for Card
        Card colouredCard = new Card ("Coloured Card","A3","654321",1.25);
        // adds coloured card item code to the testArray list
        // testArray.addCraftItemToStock(colouredCard.getItemCode());
        // creating new object instance for Glue
        Glue superGlue = new Glue ("Super Glue",25,"210987",1.50);
        // adds superGlue item code to the testArray list
        // testArray.addCraftItemToStock(superGlue.getItemCode());
        // creating new object instance for Card
        Card whiteCard = new Card ("White Card","A4","123456",0.50);
        // adds superGlue item code to the testArray list
        // testArray.addCraftItemToStock(whiteCard.getItemCode());
        // display complete stocklist
        testArray.displayCraftStockList();
        // this adds the itemCode from gluePVA to the array but
        // it comes out as the last itemCode entry 123456 rather than 789012
        // when I run the code. The problem may lie with variable itemCode
        testArray.addCraftItemToStock(gluePVA.getItemCode());
        // display complete stocklist
        testArray.displayCraftStockList();
    CraftItem.java
    public class CraftItem {
      // instance variables
      public static String itemCode;
      private double price;
      //private int stockCount;
      // constructor
      public CraftItem(String itemCodeValue, double itemPriceValue){
        itemCode = itemCodeValue;
        price = itemPriceValue;
        //CraftStock.addCraftItemToStock(itemCode);
        //stockCount++;
      // getter for itemCode
      public String getItemCode() {
        return itemCode;
      // getter for price
      public double getPrice() {
        return price;
      // setter for itemCode
      public void setItemCode(String itemCodeValue) {
        itemCode = itemCodeValue;
      // setter for price
      public void setPrice(double itemPriceValue) {
        price = itemPriceValue;
      // toString() value
      public String toString() {
        return "Item code is " + itemCode + " and costs " + price + " pounds.";
    Glue.java
    public class Glue extends CraftItem{
      // Instance variables
      private String glueType;
      private double glueVolume;
      // Constructor
      public Glue(String glueType, double glueVolume,
       String itemCodeValue, double itemPriceValue) {
            super(itemCodeValue, itemPriceValue);
            glueType = glueType;
            glueVolume = glueVolume;
      // getter
      public String getGlueType() {
        return glueType;
      // getter
      public double getGlueVolume() {
        return glueVolume;
      // setter
      public void setGlueType(String glueTypeValue) {
        glueType = glueTypeValue;
      public void setGlueVolume(double glueVolumeValue) {
        glueVolume = glueVolumeValue;
      // toString
      public String toString() {
        return glueType + ", " + glueVolume + "ml, item code is "
         + super.getItemCode() + " and costs " + super.getPrice() + " pounds.";
    Card.java
    public class Card extends CraftItem{
      // instance variables
      private String cardType;
      private String cardSize;
      // Constructor
      // added super(itemCodeValue, itemPriceValue) to call on CraftItem
      public Card(String cardTypeValue, String cardSizeValue,
       String itemCodeValue, double itemPriceValue) {
            super(itemCodeValue, itemPriceValue);
            cardType = cardTypeValue;
            cardSize = cardSizeValue;
      // getter
      public String getCardType() {
        return cardType;
      // getter
      public String getCardSize() {
        return cardSize;
      // setter
      public void setCardType(String cardTypeValue) {
        cardType = cardTypeValue;
      // setter
      public void setCardSize(String cardSizeValue) {
        cardSize = cardSizeValue;
      // toString
      // using super. to call on methods from superclass CraftItem
      public String toString() {
        return cardType + ", size " + cardSize + ", item code is "
         + super.getItemCode() + " and costs " + super.getPrice() + " pounds.";
    CraftStock.java
    public class CraftStock {
        public static int currentStockLevel;
        public static String[] craftStock;
        public static int initialStockCapacity = 10;
        public CraftStock(int initialStockCapacity) {
            currentStockLevel = 0;
            craftStock = new String[initialStockCapacity];
        public int currentStockLevel() {
            return currentStockLevel;
        public static void addCraftItemToStock(String itemCodeValue) {
            if(currentStockLevel == 10){
              System.out.println("Stock list full: cannot add new item code." +
                "\nPlease remove an item if you want to add a new one.");
            else{
            craftStock[currentStockLevel] = itemCodeValue;
            currentStockLevel++;
            System.out.println("Item added");
        public void removeCraftItemFromStock(String itemCode){
          findStockItem(itemCode);
          int i = -1;
            do {
                i++;
            } while (!craftStock.equals(itemCode));
    for (int j = i; j < currentStockLevel - 1; j++) {
    craftStock[j] = craftStock[j + 1];
    currentStockLevel--;
    System.out.println("Item removed");
    private int findStockItem(String itemCode){
    int index = 0;
    for(int i = 0; i < currentStockLevel; i++){
    if(craftStock[i].equals(itemCode)){
    index = i;
    break;
    else{
    index = -1;
    return index;
    public void displayCraftStockList() {
    if(currentStockLevel == 0){
    System.out.println("There are no items in the stock list");
    else{
    for(int i = 0; i < currentStockLevel; i++){
    System.out.println("Item at " + (i + 1) + " is " + craftStock[i]);
    Message was edited by:
    Nikarius

    An instance variable relates to an object. If you require a variable to be available across multiple objects of the same class then I suggest you declare a class variable using the static keyword in your declaration.
    HTH

  • Do I really have to create object instance before jsf can update its value?

    Hello,
    I have jsp page with following fragment:
    <h:inputText value="#{myBean.obj.value}"/>
    myBean is defined as managed bean of class MyBean:
    public class MyBean {
         private MyObject obj;
         public object getObj() { return obj; }
         public void setObj(MyObject obj) { this.obj = obj; }
    MyObject is a POJO with getter and setter for property "value".
    Now, when I display this jsp page, inputText will be empty, since getter for "obj" returned null. If I enter something in this inputText and submit the page I will get:
    PropertyNotFoundException: Error testing property 'value' in bean of type null
    This exception was thrown in PROCESS_VALIDATIONS phase. As I see, JSF is expecting getter for "obj" to return MyObject instance, where instead it returns null.
    My question is: do I really have to have already created instance of object for validation to succed?
    I know that this problem is easy to solve by placing
         private MyObject obj = new MyObject();
    in class definition or similar initialization in constructor, but..
    What if "obj" is a hibernate bean, that has a full tree of other hibernate beans as properties... In this case, creating a new instance of "obj" and initializing all of it nodes, is no more "one line of code" task, but instead 20 lines of, IMHO, unnecessary code.
    So I was wondering why is JSF unable to create new instance of object whose properties is trying to update?
    Regards,
    Igor

    Thanks for reply,
    I'm aware of jsf IoC, but this does not simplify my problem.
    In my case MyObject is class used by Hibernate and can be something like:
    public class Employee {
    private String name;
    private Workgroup workGrp;
    private Residence res;
    // ... more properties, getters, setters
    public class Residence {
    private State state;
    // ... more properties, getters, setters
    So, in order to fully create Employee instance, I have to create and set its Workgroup and Residence properties, and then create and set State inside Residence...etc. Defining all hibernate classes as managed beans, and making dependancies between them cannot solve this problem.
    Since I don't want to add constructors or initializers to hibernate classes, the only solution I can come up with is to do manual creation:
    obj = new Employee();
    obj.setWorkGrp(new Workgroup());
    obj.setRes(new Residence());
    // ...etc
    and place this code in obj's getter to be executed if obj is null. This is the reason I was wondering why can't this be done by jsf automaticly?

  • Creating object instance

    I'm trying to create a new instance of an object using data supplied from a DataInputStream.
    I can create a new instance of my object Nasjob using
    Nasjob myjob = new Nasjob("12345","smith","K");
    Using a DataInputStream I can obtain the string "12345","smith","K"
    and assign it to a variable called MYPARAMS
    When I try to substitute "12345","smith","K" with MYPARAMS
    Eg
    Nasjob myjob = new Nasjob(MYPARAMS);
    I get a compilation error.
    I'm new to java so any help greatly appreciated

    So you have a construtor:
    NasJob(String s1, String s2, String s3)
    and you are calling it with
    new NasJob(s)
    Its not going to work:
    You need to define a constructor:
    NasJob(String s)
    then do some tokenizing inside to get the three tokenized parameters in the string! The Java compiler is not clever enough to realise that the string you are passing to a constructor requiring three strings does infact contain three parameters seperated by commas!!

  • Invoked super class constructor means create an object of it?

    Hei,
    i have create one class that extends another class. when i am creating an object of sub class it invoked the constructor of the super class. thats okay.
    but my question is :
    constructor is invoked when class is intitiated means when we create an
    object of sub class it automatically create an object of super class. so means every time it create super class object.

    Hi,
       An object has the fields of its own class plus all fields of its parent class, grandparent class, all the way up to the root class Object. It's necessary to initialize all fields, therefore all constructors must be called! The Java compiler automatically inserts the necessary constructor calls in the process of constructor chaining, or you can do it explicitly.
       The Java compiler inserts a call to the parent constructor (super) if you don't have a constructor call as the first statement of you constructor.
    Normally, you won't need to call the constructor for your parent class because it's automatically generated, but there are two cases where this is necessary.
       1. You want to call a parent constructor which has parameters (the automatically generated super constructor call has no parameters).
       2. There is no parameterless parent constructor because only constructors with parameters are defined in the parent class.
       I hope your query is resolved. If not please let me know.
    Thanks & Regards,
    Charan.

Maybe you are looking for