Calling a constructor

I have an instantiated class, with the initialization code in the constructor. I want to be able to call the constructor again (to reset object data) without moving the reference to the object. Is there an easy way to do this? I don't want to have to put data initialization into a separate function.

// Java ain't no C++
void T::reinit() {
delete this;
*this = * ( new T());
}...and that ain't no C++ either ;-)
Sorry for the off-topic reply, but that code cannot stand uncorrected.delete this; Only valid for heap-constructed objects, which you can't be sure of inside the function. Will crash otherwise.
If "this" was in fact on the heap, execution might indeed reach this line:
*this = * ( new T()); ...only to crash there, since it's an illegal dereferencing of "this", which has just been deleted.
(Surviving the Access Violation, you'd then have a memory leak, since new T() will never be deleted.)
The correct C++ way of doing a re-initialization would make use of placement-new.
void T::reinit()
T::~T();
new(this) T();
}

Similar Messages

  • 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

  • How to call parent constructor from subtype body ?

    create or replace TYPE person as object(
    p_name varchar2(10),
    p_age NUMBER,
    p_status CHAR,
    p_addr addr_type,
    constructor function person ( p_name char, p_age NUMBER, p_status CHAR, p_addr addr_type ) RETURN SELF AS RESULT
    )NOT FINAL;
    -- subclass
    create or replace TYPE employee under person(
    e_number number,
    hire_date date,
    e_designation varchar2(15),
    constructor function employee ( e_name char, e_age NUMBER, e_status CHAR,
    e_addr addr_type, e_number NUMBER, hire_date date, e_designation CHAR )
    return SELF AS RESULT
    In this scenario how do we call parent constructor from employee type ?

    Can't You write complete example? Tried few variants but get nothing:(

  • Call a constructor as an array

    suppose there is a constructor that takes an argument
    public ball(int radius){
    this.radius=radius;
    now I need to call array of constructor ball(radius). how do i do it?
    thanks

    csckid wrote:
    suppose there is a constructor that takes an argument
    public ball(int radius){
    this.radius=radius;
    now I need to call array of constructor ball(radius). how do i do it?You don't really call the constructor. It gets called when you create an object using new. So to fill an array with ball objects you create the number of objects you need and assign them to the ball array elements.

  • What is the need for calling default constructor by JVM?

    What is the need for calling default constructor by JVM? why the JVM should intiializes default values to the data
    fields if the constructor is not there in our class?

    mahar wrote:
    What is the need for calling default constructor by JVM? Huh? The JVM does not need to call the default constructor. It needs to call a constructor.
    You decide which one by the way you use "new".
    why the JVM should initialize default values to the data fieldsHuh?
    ... if the constructor is not there in our class?Huh? The default constructor is always there. It may be private but it is still there.

  • Cannot call parametrized  constructor

    I have a class which extends an abstract class and have the following problem:
    - When i use the default constructor, all works fine
    - When i try to use the 'parametrized' constructor, compile fails....
    Any suggestions, sorry if i oversee any 'elementary coding'....
    calling class
    package testAbstract;
    public class FinalAbstract extends BaseAbstract {
         * Launches this application
        public static void main(String[] args) {
            FinalAbstract myApplication = new FinalAbstract();           // this works
            // FinalAbstract myApplication = new FinalAbstract(true);    // this doesn't
            myApplication.setTitle("AbstractTest");
        public void activateApplication() {
    abstract class
    package testAbstract;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public abstract class BaseAbstract extends JFrame {
        // Variables
        private static boolean isTestVal = false;
        // Swing objects and varialbles
        private JPanel jContentPane;
         * This is the default constructor
        public BaseAbstract() {
             this(isTestVal);
         * This constructor contains a parameter
        public BaseAbstract(boolean isValue) {
            System.out.print("Executing BaseAbstract(boolean isValue()");
            System.out.print("isValue = " + isValue);
            // Start Application
            initialize();
        public abstract void activateApplication();
        private void initialize() {
            setContentPane(getJContentPane());
            setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
            setTitle("MyBaseAbstractApplication");
            setSize(400,300);
            setVisible(true);
            //Validate
            this.validate();
            //Center the window
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = this.getSize();
            if (frameSize.height > screenSize.height) {
              frameSize.height = screenSize.height;
            if (frameSize.width > screenSize.width) {
              frameSize.width = screenSize.width;
            setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
        private JPanel getJContentPane() {
            if (jContentPane == null) {
                jContentPane = new JPanel();
                jContentPane.setLayout(new BorderLayout());
                jContentPane.add(new javax.swing.JLabel("Test"), java.awt.BorderLayout.CENTER);
            return jContentPane;
    }

    Thanks.
    I changed the code as in example which can be compiled now.
    So, i have to declare constructors without any code but with parameters only?
    Can i add some specific code here? If so, which code is executed?
    Now, when executing the code, the parameter is not ported..., the print.out statement shows a value of 'false' whereas i call the constructor with 'true'
    package testAbstract;
    public class FinalAbstract extends BaseAbstract {
         * Launches this application
        public static void main(String[] args) {
            boolean isValue = true;
            // FinalAbstract myApplication1 = new FinalAbstract();           // this works
            FinalAbstract myApplication2 = new FinalAbstract(isValue);    // this doesn't
            // myApplication1.setTitle("AbstractTest without parameter");
            myApplication2.setTitle("AbstractTest with parameter");
        public FinalAbstract(){}
        public FinalAbstract(boolean isValue) {}
        public void activateApplication() {
    }

  • [svn:bz-trunk] 12783: Optimizations around subtopic handling in MessageService/ ActionscriptAdapter, now we avoid calling Subtopic constructor ( which is costly) multiple times.

    Revision: 12783
    Revision: 12783
    Author:   [email protected]
    Date:     2009-12-10 06:42:14 -0800 (Thu, 10 Dec 2009)
    Log Message:
    Optimizations around subtopic handling in MessageService/ActionscriptAdapter, now we avoid calling Subtopic constructor (which is costly) multiple times.
    Checkintests: Pass - except the usual 3 failing tests.
    QA: Yes
    Doc: No
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/services/MessageService.java
        blazeds/trunk/modules/core/src/flex/messaging/services/messaging/SubscriptionManager.java
        blazeds/trunk/modules/core/src/flex/messaging/services/messaging/adapters/ActionScriptAda pter.java

  • How call the constructor of the super type in the sub type?

    Hi, everybody:
    There are two type as belowing code:
    CREATE TYEP super_t AS OBJECT (
    a NUMBER(7,1),
    b NUMBER(7,1),
    CONSTRUCTOR FUNCTION super_t
    (a IN NUMBER:=null, b IN NUMBER:=null) RETURN SELF AS RESULT
    ) NOT FINAL;
    CREATE TYEP sub_t UNDER super_t (
    CONSTRUCTOR FUNCTION sub_t RETURN SELF AS RESULT
    Because super_t has the constructor that can pass 0 to two parameters, does the constructor of the sub_t can call the constructor of the super_t to create the instance of the sub_t?
    If can, how call?
    If not, need to rewrite the code as the constructor of the super_t in the constructor of the sub_t?
    Thank you very much!

    No the supertype constructor is not automatically called (that should have been trivial for you to prove to yourself). Unfortunately, you can't call it from the subtype either (there is functionality like Java's 'super'). You could define a named method in the supertype that does the initialization and call that in both the constructors however.

  • Why Can't I call a constructor?

    Hello all,
    Why cant i call a constructor as a function?, just like any other function by its name?...
    class Test{
         Test(){
        void func(){
             Test();    // why cant i do this?
    To me it looks just like another function. So whats the wrong in calling it as a function?...

    It says "Method not found" because there is no method Test() in your class, only a constructor with that name (without parameters), as already mentioned by a previous poster. Try to replace the line by new Test(); and it should work. But note that this will create a new object of the class and so, doesn't make any sense.
    Think of constructors being only called when creating a new object. So you don't want "to call the constructor again", because the object already exists.
    Constructors and methods are really something very different. You might have a look at the Java tutorial for further details:
    http://java.sun.com/docs/books/tutorial/java/index.html

  • Enable the "calling WebIDL constructors as functions" on the web

    Hi,
    I am developing a web application using php and python. After updating the Firefox to the latest version 30.0, some functions on my app do not work anymore. I checked the change logs of Firefox and found out this change: "Disallow calling WebIDL constructors as functions on the web" caused the issue on my tool.
    So how can I fix this on the browser side since I cannot change the codes immediately right now?
    Also a suggestion: Please reverse this change on the next update of this browser since this will affect my users or else I have to greatly change the codes.
    Thanks

    Please check out where this is fixed and the Site Compatibility list in the last portion of the bug [https://bugzilla.mozilla.org/show_bug.cgi?id=916644]

  • Calling a constructor of an object that extends another object

    suppose you have the source:
    class A {
    public int x = 1;
    public int y = 5;
    public A(){y = 6;)
    class B extends A {
    public B(){}
    public B(int a) { super(a); }
    Now suppose in the main function you say
    B b1 = new B();
    I would think the value of x is 1 which it is, but the value of y is 6, why is this, I did not call the A constructor or does an object call the parameterless constructor of its superclass automatically. If that is the case, it will clarify to me why y gets the value of 6 and not 5.

    Unless you specify a super call, it will be done. The next two constructors are the same:public B () {
        x = 2;
    public B () {
        super ();
        x = 2;
    }Another thing for you to try: remove the A () constructor (but keep the A (int)) and see if B will still compile.
    Kind regards,
    Levi

  • De-serialization not calling default constructor ??

    Hi,
    I have a strange problem with serialization (de-serialization, actually):
    I have a bunch of classes that represent the model for my application.
    These classes are organized as a complex tree and come in three flavors:
    public abstract class AbstractIOCLeaf implements IOCElement {
         private String name;
         private transient boolean changed = false;
         private transient LinkedList<ChangeListener> changeListeners;
         protected AbstractIOCLeaf() {
              super();
              name = null;
              changed = false;
              changeListeners = new LinkedList<ChangeListener>();
         } //needed for Serialzation
         protected AbstractIOCLeaf(String name) {
              this();
              this.name = name;
    ...this class is a leaf: it cannot contain other sub-elements.
    public abstract class AbstractIOCList<T extends IOCElement> extends AbstractIOCNode implements ComboBoxModel {
         protected LinkedList<T> list = null;
         protected transient List<ListDataListener> listListeners;
         protected abstract T newElement(String name);     
         protected AbstractIOCList() { super();  listListeners = new LinkedList<ListDataListener>(); }
         public AbstractIOCList(String name) {
              super(name);
              list = new LinkedList<T>();
              listListeners = new LinkedList<ListDataListener>();
    ... This class holds a list of elements that are all equal.
    and finally:
    public abstract class AbstractIOCNode extends AbstractIOCLeaf implements ChangeListener, ListDataListener {
         protected AbstractIOCNode() { super(); }
         protected AbstractIOCNode(String name) {
              super(name);
    ... This class holds elements that are all different.
    The actual classes extends one of these following the pattern:
    public class StateMachine extends AbstractIOCNode {
         private StateList states = null;;
         private EventQueue fEventQueue = null;
         private StateMachine() { super(); }
         private StateMachine(String name) {
              super(name);
              states = StateList.newInstance(this);
              changed = false;
         public static StateMachine newInstance(String name) {
              StateMachine sm = new StateMachine(name);
              sm.initialize();
              return sm;
    public class StateList extends AbstractIOCList<State> {
         private StateMachine sm;
         private StateList() { super("StateList"); sm = null; }
         private StateList(StateMachine sm) {
              this();
              this.sm = sm;
         public static StateList newInstance(StateMachine sm) {
              StateList list = new StateList(sm);
              list.initialize();
              return list;
    ...etc. etc.
    I do serialization calling ObjectOutputStream.writeObject on the root object and (obviously) deserialize using ObjectOutputStream.readObject.
    The process works, but it seems that the default constructors in particular AbstractIOCLeaf() is never called while deserializing. First hint to something amiss was the fact that I always had the transient field changeListeners remaining in its default null state.
    Further investigation involving debugging and breakpointing confirmed no default constructor is called in spite of the super(); calls.
    What am I doing wrong??
    Did I miss something about serialization (apparently so, but I cannot understand what!)?
    Side issue:
    I tried substituting ObjectOutputStream.writeObject with XMLEncoder.writeObject, but then I get the error: "Class sun.reflect.misc.Trampoline can not access a member of class com.softin.IOCbuilder.model.IOController with modifiers "private"".
    Aren't those classes supposed to be equivalent?
    Is there any (fast) way to desume the offending member?
    Excuse me for the length of the post and
    Thanks in Advance
    Mauro

    Oops, nevermind. Sorry.

  • Calling Java Constructor from Oracle Stored Procedure

    Hi all,
    I have come across a situation where on insert into one Oracle database instance, a trigger will be fired which will call a procedure which in turn calls a Java constructor with 2 string arguments(The Java class is loaded into another instance of Oracle using Loadjava).
    (Note: I don't want to call a static method from the Oracle procedure)
    I have seen some examples where in using links, on insertion into a table another table of another instance can also be updated.
    for ex: "INSERT INTO testuser.sal_audit@mainlink VALUES (?, ?, ?)" where "mainlink" is a DB link between the 2 instances.
    Similarly is it possble to call the Java constructor loaded in another instance?
    I have tried in this way. It's not working.
    create or replace procedure pr_Cust_object(FeData varchar2,szDummy varchar2) as
    LANGUAGE JAVA NAME
    'CustomObject@mainLink(java.lang.String, java.lang.String)';
    end pr_Cust_object;
    Expecting help at the earliest--ASAP.
    Thanks and Regards,
    Narendra S K

    I don't know how to do that, but I would be interested in knowing how long each insert/update/delete (which ever the trigger fires on) takes.
    And the logic for rollbacks is probably really interesting.

  • 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.

  • Mock objects calling parent constructor

    I'm trying to create some tests in which I'm providing a mock object to the constructor of my test objects and testing that appropriate methods are called in the mock. The objects I'm mocking only have a few public methods so I created an inner class that extends the object I'm trying to mock and just records which method was called. However, when I run the test it fails because the mock object calls the default constructor of the object of it's parent; causing the entire application to run. I'm trying to figure out a way around this.
    Now I already know a solution that would work, creating a second constructor in the object I'm mocking which does nothing, then call the fake constructor from my mock object instead of the default constructor. The solution dosn't feel very elegent though, I'm wondering if I'm missing a simpler solution?

    dsollen wrote:
    I'm testing JMS communication between two applications. Each topic Listener has a reference to the main class of the respective applications to communicate with them.I still don't see why a call to the constructor should start the program. Change the design so that doesn't happen. You should instead provide a start method.
    Kaj

Maybe you are looking for

  • How do I change my default search engine in Safari?

    I would like to change my default search engine other than the options that's given in the Preferences. Does anyone know how to?

  • MI07,Physical Inventry posting can hit dual G/L or Double Entry posting

    HI Experts, At the time of Physical Inventry posting, we are using Tcode-MI07. After that normally two documents are generated. One is accounting document and another is material posting document. Then we hit two G/L in Accounting document, one is In

  • Can't restore Preferences

    I am running Mac OS X 10.6.8 on an iMac and recently added Time Capsule a couple months ago. Everything had been running VERY smoothly on my iMac for over a year. About a week ago I noticed that I was getting a lot of unresponsiveness / delays and th

  • Photo organization in Finder

    Hello all. At some random point iphoto stoped sorting my files by date and started sorting them by roll number. It used to sort it by year - month - day. Now there is just roll numbers. Does anyone know how to change this setting?

  • Position/size properties messed up of imported svg's in An CC 2014?

    Hello, Opening an existing project in Edge Animate CC 2014 gave specific, big negative x and y coordinates of objects on the stage, while the objects still appeared at the right place on the stage. However, trying to alter the position, the object su