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!

Similar Messages

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

  • 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

  • Dynamic classloading without default constructor

    Just wondering if anyone has done dynamic classloading using a constructor other than the default. I know that newInstance() calls the default constructor. But how would you do it without that? Thanks for the help.

    If you know that there is a constructor that takes,
    for example, a single String argument you can use
    something like this:
    Class clazz = ...; // class to instantiate
    String stringArg = ...; // argument to pass to constructor
    Constructor c = clazz.getConstructor( new Class[] { String.class } );
    Object value = c.newInstance( new Object[] { stringArg > } );
    And even better, when JDK 1.5 is released, you'll be able to write:
        Class clazz = ...;
        String stringArg = ...;
        Constructor c = clazz.getConstructor(String.class);
        Object value = c.newInstance(stringArg);Geoff

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

  • Axis client: Always creating null-element even if I dont set it

    I am using Axis client to integrate with Webmethods.
    They have a type specified with:
    <element name="x" type="string" minOccurs="0"/>
    I do not want to set the value in the field because the value is unknown for me. So I choose not to set it at all and everything would be fine if not Axis sets it for me as a null-element.
    How do I get around this? I have to do it on the client side, because the webmethods system is not changeable.

    I am using Axis client to integrate with Webmethods.
    They have a type specified with:
    <element name="x" type="string" minOccurs="0"/>
    I do not want to set the value in the field because the value is unknown for me. So I choose not to set it at all and everything would be fine if not Axis sets it for me as a null-element.
    How do I get around this? I have to do it on the client side, because the webmethods system is not changeable.

  • Can't see any objects

    I had an "interesting" problem viewing all the objects in the database
    ( couldn't see anything in the folders on the left ). I've managed to solve it
    so i decided to share it with the others...
    I created a schema on the 11g but when we ware connecting, by my mistake,
    we used all caps. We connected successfully, ran all the sql normaly, but no one could see any objects - same case in the JDeveloper!
    The solution was to log in normally - without any caps.
    This sounds like nothing special, but on the other similar database applications this works fine.
    Since I'm big fan of the SQL Devloper I wanted to contribute even by solving this
    simple bug.
    all the best...

    Yes, i am logging in with the same user!
    I have not created any object with my owner! But i 've been granted many privileges regarding other owner's objects;
    I'm using Raptor in a Windows XP platform!!
    Thank you very much!!!
    Claudio.

  • Not Able to Create database objects(Tables, etc) in Oracle 12c

    Hello Sir,
    Recently, I have installed oracle 12c in my PC. And I am able to connect with the ANONYMOUS user and connection name ORCL.
    But I am not able to create any objects in database like tables creation, it's just showing the error message like- you don't have sufficient privileges.
    Could you please help on this? How to start the work on oracle 12c database as I have worked on Oracle 11g with the SCOTT user and connection name ORCL.It was working fine. But SCOTT user is not present in 12c. Is there any other USER in 12c with the default tables like EMP table in 11g in the SCOTT USER schema?
    Please suggest, what to do?
    Thanks In Advance!!

    Hi Nishant ,
    Thanks for the reply.
        I have done all the steps as you mentioned above. I am not able to create HR user. Please check the below errors and
    please guide me on this.
    SQL*Plus: Release 12.1.0.1.0 Production on Sat Oct 5 23:46:38 2013
    Copyright (c) 1982, 2013, Oracle.  All rights reserved.
    Enter user-name: anonymous
    Enter password:
    Last Successful login time: Sat Oct 05 2013 23:46:58 +05:30
    Connected to: Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 - 64bit Production With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options
    SQL> connect sys as sysdba;
    Enter password:
    Connected.
    SQL> CREATE USER  hr IDENTIFIED BY Password#123
      2  DEFAULT TABLESPACE  hr_users
      3  TEMPORARY TABLESPACE  hr_temp
      4  QUOTA  5000k ON  hr_users
      5  QUOTA unlimited ON hr_temp
      6  PROFILE  enduser  ;
    CREATE USER  hr IDENTIFIED BY Password#123
    ERROR at line 1:
    ORA-65096: invalid common user or role name
    SQL> SELECT NAME, CDB FROM V$DATABASE;
    NAME      CDB
    ORCL      YES
    SQL> SHO CON_ID CON_NAME
    CON_ID
    1
    CON_NAME
    CDB$ROOT
    SQL> SET LINE 150
    SQL> SELECT NAME, OPEN_MODE, OPEN_TIME FROM V$PDBS;
    NAME                           OPEN_MODE  OPEN_TIME
    PDB$SEED                   READ ONLY  04-OCT-13 08.57.50.461 PM
    PDBORCL                        MOUNTED
    SQL> CONN HR/HR@PDBORCL
    ERROR:
    ORA-12154: TNS:could not resolve the connect identifier specified
    SQL> SHO CON_ID CON_NAME
    SP2-0640: Not connected
    SP2-0641: "SHOW CONTAINER" requires connection to server
    Thanks in advance!!
    Regards,
    Dharmendra Verma

  • How to create an object within the same class???

    hi im just a newbie
    i v been always creating an object from the main class..
    but how to create an object inside the same class??
    i got main and students class
    the main got an array
    Students[] stu = new Students[]
    and i got
    stu[i] = new Students(id,name);
    i++;
    but i wanna do these things inside the Students class..
    i tried ..but i got errors.....
    how to do this
    .

    javaexpert, :)
    I really have no idea what you are trying to do since you say you've always been creating an object from the main class, yet you always want to create an object inside the same class.
    I'll assume that you have an object in the main class that you are trying to access from the Students class.
    If you are trying to access objects that are contained within the main class FROM the Students class, then know that there are two ways of doing so, one being static, and the other dynamic (look up definitions if unclear):
    1.) make the objects in the main class both static and public and access the the objects using a convention similiar to: Main.object; It's important to note that Main is the name of your main class, and object is a static object. There are better ways of doing this by using gettter/setter methods, but I'll omit that tutorial.
    2.) Create a new instance of the main class and access the objects using a similiar fashion: Main myInstance = new Main(); myInstance.myObject;
    You should really use getter and setter methods but I'll omit the code. In terms of which approach is better, step one is by far.
    I don't mean to be condecending, but you should really brush up on your programming skills before posting to this forum. This is a fundamenetal concept that you will encounter time and time again.

  • How to create a new user without any sample objects from any other user?

    Question as the title.
    I had the example dababase installed when I installed the Oracle database.
    Every time, when I create a new user, there will be some example objects coming
    with the new user.
    How can I remove these objects from the new user?
    Or, how can I create a new user without the example objects?
    Thanks in advance.

    I think the easiest way for you would be to use OEM.
    Just locate each object that you want to remove and right click->remove. Don't bother doing this for any indexes as these will be removed when you drop the corresponding tables.
    If you want to try command line through sqlplus then identify the objects you want to remove by selecting from the user_objects view while logged in as this user. This will give you the name and type of object. Then issue the relevant drop command.
    It's probably worth making sure you have a valid backup first, just in case things go wrong!

  • Creating an instance of a class with no default constructor

    Hello gurus,
    I wrote my own serialization and RMI protocol for both C++ and Java that follows closely what the default Java version does. I'm trying to recreate an object on the Java side that was sent over the wire. The first step is to create an instance of the class. How do I create an instance of a class that has no constructor (i.e. the only instances are static, created by the class itself and returned by static methods) or one that has no default constructor (like Integer)? The Java serialization seems to support it but the reflection API doesn't seem to have any support for this (i.e. Class::newInstance() and Constructor::newInstance()). It seems that through the standard API you can only create an object via one of its constructors. There must be a "hidden" method somewhere that allows the Java serialization to create an object without calling a constructor - where is it?
    Dominique

    There must be a "hidden" method
    somewhere that allows the Java serialization to create
    an object without calling a constructor - where is
    it?You are correct, the way in which the Serialization creates Objects is "hidden" deep within the runtime.
    If it were not hidden, you would be able to find it, and use it to violate the integrity of the VM.

  • Color blend without creating intermediate object

    I suspect the answer to this may be painfully obvious, so please put any "Doh!" thoughts on hold.
    I have two overlapping objects of very different shapes, each with a gradient. I want to smooth the color transition between them so that it looks as if there's a single surface.
    When I use the Blend tool Illustrator not only blends the colors, it creates an intermediate object as well. Is there a way simply to do the color without creating a new object?

    Blends, by definition, create intermediate objects between the original key objects. A Blend creates objects. It does not create color ramps independent of objects. That's what a graduated fill does, but grad fills are very limited in AI compared to just about all of its competing programs.
    Mesh Gradients can create multi-directional grad fills. But using the feature can easily become very tedious depending upon the specifics of what you are trying to do.
    You need to describe what you are actually trying to do.
    It sounds like you may be trying to build simple highlights and shadows to "model" what is to look like 3D surfaces. Using ordinary Blends is the most common way to do that. If that's what you are trying to do, the following may help:
    -To avoid the unsightly sawtooth or twisting or spiking "giveaways" of highlight / shadow blends, they should be made between paths which contain the same number of points.
    Using paths with equal number of points may require stacking two or three separate blends, instead of assuming the whole start-to-end color ramp has to be accomplished in a single Blend. For example: Start with the underlying shape, and create a Blend that goes from the outer color (rearmost) color to a midtone color (frontmost). Those two paths have the same number of points. Then, create a separate pair of paths (again with same number of points) for a separate highlight. That blend goes from the midtone color (rearmost) to the highlight color (frontmost).
    -Make sure the two paths used in the Blend have the same direction.
    -You can "index" two corresponding points on the two paths being used for a Blend by directSelecting a point on each path before creating the Blend.
    -Realize that Blends are not limted to paths that have solid fills. You can Blend between paths that have Gradient Fills. Many seemingly complex shading problems can be accomplished with simple Blends by just blending between two paths that have the same number of points, but have slightly different grad fills.
    -Specified Steps is almost always the best Blend option to use for modeling highlights/shadows. But use common sense. Do not assume that 256 steps are required to get the "smoothest" color transition. For example, if the start-to-finish color ramp of a highlight only spans 10% of a spot color, nothing is gained by using 256 steps. A mere 10 steps will probably do just fine. (Can your eye discern a smaller-than-1% change in halftone dot size?)
    Similarly, even if the colors are radically different, 10 or 20 steps may be just fine if the
    distance spanned by the Blend is small. (Can your eye detect 256 different different-shaped edges within a quarter-inch span?
    JET

  • Create POJO instance in fxml with no default constructor

    My question is that how to create POJO instance in fxml that has no default constructor. I am creating pie chart data object in fxml like this
    *<fx:define>*
    *<PieChart.Data fx:id="data" >*
    *<name>java</name>*
    *<pieValue>20.2</pieValue>*
    *</PieChart.Data>*
    *</fx:define>*
    since there is no default constructor how to create this object fxml?
    Edited by: 988476 on Feb 16, 2013 6:21 AM

    There must be a "hidden" method
    somewhere that allows the Java serialization to create
    an object without calling a constructor - where is
    it?You are correct, the way in which the Serialization creates Objects is "hidden" deep within the runtime.
    If it were not hidden, you would be able to find it, and use it to violate the integrity of the VM.

  • ADF Task Flow Binding - Refresh ifNeeded being invoked even WITHOUT any Parameter change

    Using JDeveloper 11.1.1.6.0
    Issue: Task Flow Binding property "refresh = ifNeeded" seems to be triggered even without the mutation of the input parameter.
    As per definition, "ifNeeded: refresh the ADF Region if the value of a task flow binding parameter changes." (Reference: 17.5 Refreshing an ADF Region)
    Now for the setup which reproduces the issue.
    I'll focus at the fragment bounded task flow level and will skip the jspx side.
    taskflow: main-flow.xml
    contains a single fragment mainFgmt.jsff
    has a managed bean defined SampleBean.java as pageFlow scope.
    taskflow: sub-flow.xml
    contains a single fragment subFgmt.jsff
    has an inputParameter SampleBean.java (because it is an input parameter, by default it will be at pageFlow scope)
    !important - has a nested taskflow (task flow call as defined in the component pallete) called inner-flow (see below)
    the nested taskflow is the default activity
    the nested taskflow has an outcome pointing to subFgmt where outcome = "return"
    taskflow: inner-flow.xml
    contains a single fragment called stop.jsff
    has a return activity without outcome = "return"
    stop.jsff has a navigation pointing to the outcome.
    Finally mainFgmt.jsff has a task flow binding (pageDef)
    with id = "sub-flow.xml"
    refresh = "ifNeeded"
    parameter SampleBean being submitted as sub-flow's input parameter. (id=sampleBean, value=#{pageFlowScope.mainSampleBean})
    Assume that code compiles.
    In this scenario where the only tricky condition is the inner nesting (defined by !important), when the inner nesting decides to invoke its outcome to visit sub-flow's fragment, mainFgmt is restarting its taskflow which makes sub-flow start over again.
    Another way of saying it is, if sub-flow starts a nested activity and that nested activity exits out to utilize sub-flow's view. The high level definition which is mainFgmt's refresh ifNeeded is restarting sub-flow.
    In the above example if you notice, the bean (SampleBean) is not really being utilized except that it is completing the purpose of refresh=ifNeeded. This scenario is only to simplify the setup - in practical use this bean will be mutated to be utilized as a refresh mechanism.
    Now interestingly, if I change the pattern a bit then the issue will not happen:
    Don't use the nested taskflow (inner-flow) as the default activity, let a fragment of sub-flow hold the initial view.
    Navigate to the nested flow.
    Exit nested flow.
    Everything works.
    Now in this scenario, it seems like the sub-flow needs to have a view established first for it to be properly be used.
    So my questions are as follows:
    Can I consider the behavior of the refresh=ifNeeded as a bug in this usecase?
    Would it be better to utilize a different way of refreshing (maybe combination of refresh condition) to get around the issue?
    Is the use of the task flow as defined logical or does it cross any boundary or best practice that might be causing this behavior?

    Hi,
    actually you lost me in your description due to complexity. I lived under assumption that sub-flow already is a region on a view in main flow, but then you sad that
    "!important - has a nested taskflow (task flow call as defined in the component pallete) called inner-flow (see below)"
    which then confused me as to I have no idea if inner flow now is the second level nesting or first level nesting (should be second level nesting). If sub-flow is a region then having "has an inputParameter SampleBean.java (because it is an input parameter, by default it will be at pageFlow scope)"  is an unnecessary broad scope because the region wont live longer than view scope.
    Anyway, it seems that a region refresh is triggered by the lifecycle involved, which can be by design or a bug. I suggest you file a Service Request with support and provide a test case as purely from the description, its hard to parse and understand what is going on.
    Frank

  • Is there any way I can program "Capture" to save pnp.picts always under the same name, without a date ?

    Is there any way I can program "Capture" to save pnp.picts on the desk, but always under the same name, without a date ?
    It may be sound weird, but I use it in a very special way, and I would like, like photoshop, that capture just replace
    the previous pict by the new one..without any warning.
    Pierre

    There is no way to go back from an XFA form to an Acroform even with Acrobat Pro, still less with Acrobat. You either need to remake the form, or change your plans to use a third party viewer - Adobe have an excellent range of programs they would like you to use!

Maybe you are looking for

  • XI Integration scenario for material replication from SRM to SRM-MDM

    Hi Guys, We are working with the following landscape: SRM Server 5.5 ECC 6.0 SRM-MDM 5.5 SP6 PI 2005_1_700 SP0006 I have a question for you about replication of the material master form SRM EBP to SRM-MDM. In XI we are trying to configure this scenar

  • FrameMaker and Photoshop ExtendScript Example

    Hello All, It seems that there was an example of using Photoshop in a FrameMaker ExtendScript script, but I don't remembe where I saw it. My intention is to get the path of an imported image in FrameMaker, use Photoshop to convert it to another forma

  • Call function defined in other class

    Hi.. I am new to Java programing . I want to know how to call a function defined in second class from first class. Please help me.

  • My ipod does not play in the left earbud.

    I have had a first generation ipod nano for about a year and a half now, and, recently, it has been unable to make sound out of my left earbud. I have tried three different sets of earbuds on it, and the same problem has occured. Am I correct in thin

  • Can I open CS3 files in Cs6

    Can I open CS3 files in Cs6 For InDesign Also is CS6 Compatible in OS X 10.10