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

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!

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

  • ORA-02315: incorrect number of arguments for default constructor

    I was able to register the XML schema successfully by letting Oracle creating the XML Types. Then when I try to execute the create view command the ORA-02315: incorrect number of arguments for default constructor is always raised.
    I tried using the XMLTYPE.createXML but it gives me the same error.
    Command:
    CREATE OR REPLACE VIEW samples_xml OF XMLTYPE
    XMLSCHEMA "http://localhost/samplepeak4.xsd" ELEMENT "SAMPLE"
    WITH OBJECT ID (ExtractValue(sys_nc_rowinfo$, '/SAMPLES/SAMPLE/SAMPLE_ID')) AS
    SELECT sample_t(s.sample_id, s.patient_info, s.process_info, s.lims_sample_id,
    cast (multiset(
    SELECT peak_t(p.peak_id, p.mass_charge, p.intensity, p.retention_time,
    p.cleavage_type, p.search_id, p.match_id, p.mass_observed,
    p.mass_expected, p.delta, p.miss, p.rank, p.mass_calculated,
    p.fraction)
    FROM peak p
    WHERE s.sample_id = p.sample_id) AS PEAK107_COLL))
    FROM sample s;
    Can someone help me.
    Thanks
    Carl

    This example runs without any problems on 9.2.0.4.0. Which version are you running? And which statement causes the error message?

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

  • Reflection: get an instance of a internal class by default constructor

    Hi there
    first the structure (reduced):
    public class ConvertionFactors { //singelton
    private HashMap<String,Class> factors = new HashMap<String,Class>();
    private class M_TO_FT implements DataFilter{
    public double convert(double value) {
    return value*M_IN_FT;
    public DataFilter getFilter(String from, String to)
    String name = from.toUpperCase()+convertionMethodNameSeparator+to.toUpperCase();
    Class c = factors.get(name); //retrieve the class
    Object o = c.newInstance(); //generate a instance.... not working
    return (DataFilter)o;
    The problem i want an instance of the internal class without defining a construktor like
    public M_TO_FT(){} because there are many classes like this one :-(
    (that was already working with a constructor that wants an instance of the container class.... thats what i am missing in the call c.newInstance() which uses the default constructor (i gues))
    i want something like
    new M_TO_FT() ; just the reflection version of it which calls the default constructor
    thanks for help

    well i get a Exception like this:
    java.lang.InstantiationException: com.eads.jpinfinity.data.unit.ConvertionFactors$M_TO_FT
         at java.lang.Class.newInstance0(Class.java:335)
         at java.lang.Class.newInstance(Class.java:303)
         at com.eads.jpinfinity.data.unit.ConvertionFactors.getFilter(ConvertionFactors.java:315)
         at com.eads.jpinfinity.data.unit.junit.ConvertionFactorsTest.testGetFilter(ConvertionFactorsTest.java:50)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at junit.framework.TestCase.runTest(TestCase.java:154)
         at junit.framework.TestCase.runBare(TestCase.java:127)
         at junit.framework.TestResult$1.protect(TestResult.java:106)
         at junit.framework.TestResult.runProtected(TestResult.java:124)
         at junit.framework.TestResult.run(TestResult.java:109)
         at junit.framework.TestCase.run(TestCase.java:118)
         at junit.framework.TestSuite.runTest(TestSuite.java:208)
         at junit.framework.TestSuite.run(TestSuite.java:203)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:421)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:305)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:186)
    i think because i never told the method which is the containing class for this internal class. if i defina a constructor in the inner class it always needs a instance of the containter. by calling c.newInstance() there is no relation to the container class and because the inner class cant exist without the outer class it may not be constructed.
    It is possible to get an instance with "new FT_TO_M();" (the traditional way) with the default constructor but jet i have not found a way to get a instance of a inner class with reflection without defining a constructor.

  • How to implement public default constructor for type

    i copy the servicestack dll from old project for redis 2.6, without using nuget
    i add new() but can not compile
    without new(), it has error , requires public default constructor
    type LogicDataBase =
    { mutable BitKeyFunctionValue1 : Dictionary<String, Dictionary<expr, expr>>;
    mutable PathList1 : Dictionary<expr list, expr list>
    mutable AllImplicationKeyList1 : expr list
    new() = LogicDataBase(BitKeyFunctionValue1, PathList1, AllImplicationKeyList1)
    let redisClient1 = new RedisClient("localhost")
    let d1 = {
    BitKeyFunctionValue1 = BitKeyFunctionValue
    AllImplicationKeyList1 = AllImplicationKeyList
    PathList1 = PathList
    redisClient1.Store<LogicDataBase>(d1)
    redisClient1.Save()
    let redisClient2 = redisClient1.As<LogicDataBase>()
    let rediskeys : List<String> = redisClient2.GetAllKeys()
    for kk3 in rediskeys do
    let d2 : LogicDataBase = redisClient2.[kk3]
    BitKeyFunctionValue <- d2.BitKeyFunctionValue1
    AllImplicationKeyList <- d2.AllImplicationKeyList1
    PathList <- d2.PathList1
    let debugBitKeyFunctionValue2 = BitKeyFunctionValue
    let debugAllImplicationKeyList2 = AllImplicationKeyList
    let debugPathList2 = PathList
    computing nightmare

    is there an example about this for this case?
    i see that type is also a class, where is wrong?
    type LogicDataBase =
    { mutable BitKeyFunctionValue1 : Dictionary<String, Dictionary<expr, expr>>;
    mutable PathList1 : Dictionary<expr list, expr list>
    mutable AllImplicationKeyList1 : expr list
    new() = LogicDataBase(BitKeyFunctionValue1, PathList1, AllImplicationKeyList1)
    computing nightmare

  • Require default constructor

    Although I doubt there is, I would like to know if there is a way to require subclasses to implement the default constructor. I am retrieving String class names from a data file and creating objects with the combination of Class.forName(...) and newInstance() (also from Class class). I just wanted to create them without having to deal with various combinations of constructors.

    CharanZ wrote:
    Java Creates a default constructor for every class you create, Unless you override it.Except that a) C'tors are not inherited and thus cannot be overridden, and b) If you explicitly define any c'tor, then the compiler no longer provides the default.
    So no need to worry about it.Except that there's no way to do what the OP asks, except, as already pointed out, by documentation and trusting the subclass author to follow it.

  • Inheritence without overriding constructor??

    hi every body
    my question is how to inherit from class without writing the constructor, even i dont want to use super keyword
    for example:
    public class MyText extends JTextField
    public void setText(String txt)
    }

    If the super class has a default constructor (public with no arguments) than you don't need to write a constructor in the derived class in this case an implicit default constructor will be used in all other cases you have to provide a constructor.

  • SMARTBAR in FORMS 9i without DEFAULT menu

    I need in my Forms 9i the SMARTBAR without DEFAULT menu.
    DEFAULT menu and DEFAULT&SMARTBAR menu is possible, why not a SMARTBAR menu (internal)?
    Regards
    Friedhold Matz

    The reason that there is no Smartbar on it's own is because the smartbar is driven off the menu - Menu Items can expose themselves on the smart bar if required, but any smartbar item has to be in the menu (but it can be invisible).
    So to only have smartbar would involve a menu full of only invisible items, but that would mean that peoplw would not be able to add their own menus to co-exist with the smartbar.
    You can always edit the menudefs.mmb file (it comes with the 6i demos which you can pull off OTN)

  • Is a dynamic codebase without JnlpDownloadServlet possible?

    Is it possible to have a dynamic codebase without deploying a servlet?
    Seems reasonable to me. The cache should always know where the original source for the jnlp file ....
    <jnlp spec="1.0+" codebase="codebase of original source this file" >
    </jnlp>
    I am attempting to minimize server side code and was thinking this was possible because of this statement made here : https://jdk6.dev.java.net/testProperty.html
    "In 6u10-b13, we introduce new Java system properties to support the usage of version download and Pack200 without any server side requirements."
    It seems to me that without some mechanism for dynamic codebase the new properties jnlp.packEnabled and jnlp.versionEnabled are kind of pointless since server side code will still be required in most situations. Statically coding the codebase attribute for every deployment is not a viable solution for me.

    Thanks for responding Andy.
    I was thinking that if the run-options of javaws would support the -codebase option (as with the import option), and the browser were to launch with that flag, then it could override the codebase in the jnlp file. Maybe too many moving parts there? ........
    I've been working with the -import and -codebase options in attempt to minimize the server side servlet requirement.
    Basically my thought is :
    Have the jnlp file on server with no codebase attribute.
    Use a signed applet to bring the jnlp file down from the server and write it to local disk (somewhere temporary) adding the codebase attribute along the way. Then launch the javaws with -codebase and -import flags to install the application.
    So far it seems to be working but it's been a bit of a struggle. Viewing the cached jnlp file I see that it has the codebase attribute correct and the application does launch.
    I am wondering if I update the jnlp file on the server, will the codebase in the cached file still be used? or will I need to force another -import?

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

  • Dynamic Classloading

    Hello all,
    Could someone tell me a practical way to setup dynamic classloading in an EJB app? I'd like to set it up such that all of the shared codebase is deployed within the same ear with the EJB application. Is this practical or does dynamic classloading require the use of an external web-server? Right now I am trying to use the rmi.server.codebase system property via the %JAVA_OPTS% env. variable on appserver start-up to point to a servlet deployed in a .war my .ear. What is the practical approach? Thanks in advance.
    Cliff

    Thank you crackers,
    You've cleared alot for me. So if I follow what you're saying then my problem boils down to how my client talks to the server. And the principles of EJB state that the communication details are left to the vendor. All I have to do then is get my home interface via JNDI. This assumes of course that the stubs are available on the client.
    Now don't get me wrong here, I'm not trying to debate the advantages of EJB. I'm just trying to illustrate my dillemma and find a plausible solution. In my scenario I'm not really all that concerned with the transport layer (well I am concerned with the leaky abstractions therein but that's another story). I'm primarily concerned with versioning issues. I cannot maintain classes installed on the client as they could potentially fall out of date with the server. I need a dynamic classloading mechanism, which I thought would be provided with EJB as it is with RMI. I just naturally assumed it would be since EJB is typically (though not always, as you point out) layered always RMI. If you're saying that there is no such facility then I will have to find an alternative solution for my problem. You see I have no choice and I must concern myself with the underworkings of EJB as there are leaky abstractions within the technology. While it is a powerful technology it does not solve all of my problems. Also, I need to fill these holes in a vendor neutral way.
    Cliff

  • Selective member import/export using dllexport and default constructor

    We can only export some methods in the class(https://msdn.microsoft.com/es-es/library/8d7d1303-b9e9-47ca-96cc-67bf444a08a9%28v=vs.100%29)
    What if we export only some methods in the class and not exported the default constructor(Will it get generated by the compiler in external app which use this dll?).The class may have some private data member as well which are not exposed in the published
    header file(Which we distribute with DLL).
    How the memory gets allocated to those private data members which are not exposed as the default constructor is not exported? 
    Niranjan

    We can only export some methods in the class(https://msdn.microsoft.com/es-es/library/8d7d1303-b9e9-47ca-96cc-67bf444a08a9%28v=vs.100%29)
    What if we export only some methods in the class and not exported the default constructor(Will it get generated by the compiler in external app which use this dll?).The class may have some private data member as well which are not exposed in the published
    header file(Which we distribute with DLL).
    How the memory gets allocated to those private data members which are not exposed as the default constructor is not exported? 
    Niranjan

  • Failing with 'no-arg default constructor' on @XmlTransient

    Hello,
    I have a simple exception I want to serialize to xml like this:
    public class Main {
    @XmlRootElement
    static public class SomeException extends RuntimeException {
    private Integer someAdditionalInformation;
    public SomeException() {
    public SomeException(Integer someAdditionalInformation) {
    this.someAdditionalInformation = someAdditionalInformation;
    public Integer getSomeAdditionalInformation() {
    return someAdditionalInformation;
    public void setSomeAdditionalInformation(
    Integer someAdditionalInformation) {
    this.someAdditionalInformation = someAdditionalInformation;
    @XmlTransient
    @Override
    public StackTraceElement[] getStackTrace() {
    return super.getStackTrace();
    public static void main(String[] args) {
    try {
    JAXBContext jaxbCtx = JAXBContext.newInstance(SomeException.class);
    Marshaller m = jaxbCtx.createMarshaller();
    m.marshal(new SomeException(5), System.out);
    } catch (JAXBException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    But I get the following exception:
    com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
    java.lang.StackTraceElement does not have a no-arg default constructor.
    this problem is related to the following location:
    at java.lang.StackTraceElement
    at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()
    at java.lang.Throwable
    at java.lang.Exception
    at java.lang.RuntimeException
    at jaxbtest.Main$SomeException
    Does this seam like a JAXB bug ?
    @XmlTransient should make JAXB just skip that property.
    Is there ant way to workaround this ?
    PS. Where did the JAXB team fly away ? jaxb.dev.java.net is blank

    Looking at your log it is clear that, you are populating Xellerate Type=null. This is mandatory field and can't be null. However, when you create user using UI, the default value "End-Users" is being passed by default, because we have the corresponding field "Design Console" access check box at oim user profile.
    Just map the constant value for trusted recon
    Xellerate Type=End-Users
    --nayan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Httpd fail to start after Zend Core installation

    Hi! I need Zend, so I installed it using this instruction. The problem is that httpd daemon faild to start after that. Here is my /etc/httpd/conf/httpd.conf: # This is the main Apache HTTP server configuration file. It contains the # configuration di

  • Good News for Window User DVD to IPOD

    you need to use dvd decrypter then videora ipod converter. these step will bring down from 4g movie to around 700mb. when you using videora ipod converter make sure the audio check with channel 6. then if you want to compress more then you need to bu

  • How do I open a photo and post online?

    Good evening, how do I open a photo and post online if it's Adobe Reader?

  • Unable to connect JAVA with Oracle

    I have jdk1.6 and oracle installed on my machine but unable to connect java with database have classes12.jar and ojdbc14.jar my environmental variables in respect to this are : JAVA_HOME= C:\Java\jdk1.6.0_04 JRE_HOME=C:\Java\jdk1.6.0_04 PATH=J:\oracl

  • BW Information need please

    Hi, I am new in BW or BI, I would like to know about onsite issue in BW, what kind of issue mostlay comeup in BW in any company!!! I understand its not right question but I want to know little bit how to check performance, of BW some admin Tcode or m