Set fields of derived class in base class constructor via reflection?

Does the Java Language Specification explicitly allow setting of fields of a derived class from within the base class' constructor via reflection? The following test case runs green, but I would really like to know if this Java code is compatible among different VM implementations.
Many thanks for your feedback!
Norman
public class DerivedClassReflectionWorksInBaseClassConstructorTest extends TestCase {
abstract static class A {
    A() {
        try {
            getClass().getDeclaredField("x").setInt(this, 42);
        } catch (Exception e) {
            throw new RuntimeException(e);
static class B extends A {
    int x;
    B() {
    B(int x) {
        this.x = x;
public void testThatItWorks() {
    assertEquals(42, new B().x);
    assertEquals(99, new B(99).x);
}

why not just put a method in the superclass that the subclasses can call to initialize the subclass member variable?In derived classes (which are plug-ins), clients can use a field annotation which provides some parameter metadata such as validators and the default value. The framework must set the default value of fields, before the class' initializer or constructors are called. If the framework would do this after derived class' initializer or constructors are called, they would be overwritten:
Framework:
public abstract class Operator {
    public abstract void initialize();
}Plug-In:
public class SomeOperator extends Operator {
    @Parameter(defaultValue="42", interval="[0,100)")
    double threshold;
    @Parameter(defaultValue="C", valueSet="A,B,C")
    String mode;
    public void setThreshold(double threshold) {this.threshold = threshold;}
    public void setMode(String mode) {this.mode = mode;}
    // called by the framework after default values have been set
    public void initialize() {
}On the other hand, the default values and other metadata are also used to create GUIs and XML I/O for the derived operator class, without having it instantiated. So we cannot use the initial instance field values for that, because we don't have an instance.

Similar Messages

  • Accessing private field of Derived object in Base class

    Hi,
    I have this piece of code I wrote a while ago to test something. The issue is accessing a private field of Base class in Base but of a Derived object.
    Here is the code:
    class Base
         private int x;
         public int getX()
              return x;
         public int getX(Derived d)
              // return d.x;
              return ((Base) d).x;
    }The commented code does not work but casting d to Base does.
    Can someone please explain the reasoning for this.
    Forgot to mention that the compilation error is that x has private access in Base.
    Thank you.
    Edited by: 953012 on Apr 1, 2013 8:42 AM

    >
    As I understand the explanation says that you can access any private member within the code of the class that encloses the private member. So in this case x is the private member and the line of code (return d.x) is in Base which encloses the private member. Does it have to do with the fact that the Derived class does not in fact inherit the private members of Base?
    >
    It has to do with the entire quote from the spec
    >
    A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses
    >
    Your code is
    public int getX(Derived d)
              // return d.x;
              return ((Base) d).x;
         }The 'Derived' class is NOT 'the top level class that encloses the declaration of the member'. It does NOT inherit 'x' which is a private member of 'Base'. As far as the 'Derived' class is concerned 'x' does not exist.
    >
    If outside Base code I have Derived d = new Derived() and I call d.getX() then isn't that like calling d.x in myX()?
    >
    How is that the same? 'Base' owns 'x' and can do whatever it wants with it. 'Derived' has no knowledge of 'x' and CAN NOT access it.

  • How to call derived class to base class

    Hello everybody,
    I create a GUi application in java swing. Now i want to navigate between the screen but the timing between the screen is very slow bcoz i imported the class from package to another package. Now i want to extends one package to another package to reduce the navigation time but it saying error bcoz i cant able to call my derived class to base class. if anyone know the answer for this please answer this immediately.
    If any other method is there to optimise the navigation time please tell me
    by
    (kamal)

    Sorry, I've got major difficulties understanding your query:
    I create a GUi application in java
    ication in java swing. ok
    Now i want to navigate between
    the screenwhat? switch screens? display a different dialog?
    but the timing between the screen is very
    slowtiming? do you mean the time it takes to display a different dialog?
    bcoz i imported the class from package to
    another package.how did you come to the conclusion that that is the reason for the slowness? Did you do any profiling or is this just guess-work?

  • Export for AS: Class vs Base Class

    when i export a movie clip for actionscript, what are the differences between Class & Base Class?  i see most tutorials change Base Class and leave Class as the name of the movie clip defined in the library.

    the main use of the base class is to extend it so many different classes can share it's functionality.
    but even when not needed as a super class, the base class is also helpful when you want to instantiate many different objects using code and you don't want to write/compile many different class files.
    if flash finds you failed to write a class file (for every class exported for actionscript), flash writes a default class files for you.

  • Owner Class and Base Class ?

    hi,
    What is an Owner class and base class?
    thanks,
    Hanu

    Hi,
    the question is related to oracle java class or samething else?
    I dont understand your question.
    Regards,
    Tom

  • Can a derived class catch base class object

    can a derived class object catch a base class object
    e-g if i have a class
    class Test {
    // code
    }and
    class Test2 extends Test {
    }and lets say there is a method that return an object of Test (base class), so is it possible to write
    Test2 t=getTestObj(); // i-e subclass holding base class objectif its not.. how can we do so? so that derived class should hold base class object....

    sorry..
    here is how it goes
    i have a function a class
    public Test getObj() {
    // code
    }The constraint is that i cant change the implementation of this above function.
    Now when i call this function, it returns me a Test object. But i cant do
    Test t=getObj();because the Test class is written purely in java whereas i want to use write a new Test class that implements the same functionality [using the above given function] in JNI.
    so what i did, i created a new package [nativ] and created a class "Test" in that. But since i have to use the function that returns me Test and not "nativ.Test", so what i did, i inherited nativ.Test from "Test" so that the object might resolve the reference.
    So this is it.. that i cant modify the function and i need some way to do it.. plz reply

  • Objective-C class without base class

    I'm in doubt about the sense of letting a class to have no base class (neither NSObject nor Object).
    I have observe that in this case you could not send messages to the object, so you can't use:
    Point* p =[[Point alloc]init];
    But you can use:
    Point* p = (Point*) malloc(sizeof(Point));
    And access attributes of the object:
    p->x = 5;
    Is there any other advantage of using classes in this way (instead of a C struct)? Why language designed allowed this feature?
    Greeting: Fernando

    I would guess that it is because of it's C roots. Essentially all objects in obj-c are C structs. There is nothing really preventing a person creating their own NSObject like root class and using that in their framework.

  • Extending class + accessing base class's children

    Hello.
    I'm trying to create a sort of info and tool panels for a project, similar to the ones on the Adobe Suite's products. They'll have a tab that you can double click to open or close them and the panel's title will be on this tab.
    So I created a MovieClip called MainPanel and inside it I placed a textfield called txtTitle and a rectangular MovieClip called mTab. I duplicated the MainPanel twice on the stage, called them PanelA and PanelB, and added individual elements to them, but kept the txtTitle and mTab.  I edited PanelA and PanelB's linkage options to link them to specific custom classes.
    First I created a base class for the MainPanel.
    package com.panels{
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        import fl.text.TLFTextField;
        public class MyPanel extends MovieClip {
            public function MyPanel ():void {
                txtTitle.mouseEnabled = false;
                mTab.doubleClickEnabled = true;
                mTab.addEventListener(MouseEvent.DOUBLE_CLICK, clickedPanel);
    And then the classes for Panel A and B, which extend the MainPanel.
    package com.panels{
        import com.panels.MyPanel;
        public class PanelA extends MyPanel {
            public function PanelA ():void {
    When I test the movie, I get an error saying "Access of undefined property txtTitle" (and the same for mTab). If I just link PanelA to the MainPanel class it all works - I got it to open, close, dragged it with the mouse... I can access mTab, txtTitle and anything else already on the stage. But if I extend the class, I no longer can. Does anyone know why this happens and the best way to get it to work? Thank you.

    Still didn't do the trick, I even tried building a project from scratch with just the classes I mentioned in my example and nothing else, and then a second version where I have all files on the same directory. Not sure if it might have something to do with this being for an AIR app.
    I have found a solution that seems to be working. My new MyPanel class:
    package com.panels{
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        import fl.text.TLFTextField;
        public class MyPanel extends MovieClip {
            private var _title:TLFTextField;
            private var _tab:MovieClip;
            public function MyPanel ():void {
                _title = MovieClip(getChildByName("txtTitle")); //If I don't cast the result as a MovieClip I get an error
                _tab = TLFTextField(getChildByName("mTab")); //Same for the TLFTextField
                _title.mouseEnabled = false;
                _tab.doubleClickEnabled = true;
                _tab.addEventListener(MouseEvent.DOUBLE_CLICK, clickedPanel);
    Still I'd like to understand why I need to go through these hoops so I don't make the same mistake again.

  • To access a method frm a class derived frm a base class with the same name

    Here' s an example:-
    class TestA {
    public void start() {
    System.out.println("TestA");
    class TestB extends TestA {
    public void start() {
    System.out.println("TestB");
    }In main method I do this:-
    TestA testA = new TestA();
    TestB testB = new TestB();
    ((TestA)testB).start();Output :-
    TestB.
    Now when i define the method as static :-
    class TestA {
    public static void start() {
    System.out.println("TestA");
    class TestB extends TestA {
    public static void start() {
    System.out.println("TestB");
    }Then output is :-
    TestA.
    Can anyone let me know that when i say ((TestA)testB).start(); i.e i am type casting TestB obect to it base call then TestA should be printed but it doesn't print but when i declare method as static is does print TestA.
    Thanks,
    Heena

    >
    >
    Secondly, when i say ((TestA).testB).start(); output is TestB. But when i define start() method as static output is TestA. I need clarity for the same.In the static case, all that the compiler is interested in is the class of the expression before the ".". Because you've put in an explicit cast the type of expression is assumed to be TestA the compiler doesn't know what kind of object will actually be referenced at runtime. In the static case which method is called is determined at compile time.
    In the instance method case what determines the method called is determined the class of the actual, run time, value of the expression, and despite your cast, the actual value is still a reference to a TestB instance, so the TestB method is called. In the instance case which method called is determined at run time.

  • How to instantiate class via reflection

    Hi, I want to generically instatiate classes, but obviously Class.newInstance only works if the class has a public no args constructor. Is there any way to instantiate classes without such a constructor via reflection? It would be sufficient for me if I could use a private no args constructor.
    I already tried the following:
    Class clazz = Class.forName( "classname" );
    Constructor constructor =
    clazz.getDeclaredConstructor( new Class[] { } );
    constructor.setAccessible( true );
    object = constructor.newInstance( new Object[] {} );
    But it, too, yielded to an IllegalAccessException.

    Class clazz = Class.forName( "classname" );
    Constructor constructor =
    clazz.getDeclaredConstructor( new Class[] { } );
    constructor.setAccessible( true );
    object = constructor.newInstance( new Object[] {} );
    But it, too, yielded to an IllegalAccessException.constructor.setAccessible( true );
    is the call that generates the IllegalAccessException. Your code must be allowed to supress access checks. This is always the case if you don't have a security manager, otherwise the security manger's checkPermission method is called with an ReflectPermission("supressAccessChecks") argument.
    Either that or the getDeclaredConstructor throws the exception, in that case your code must be allowed to "check member access".
    Hope it helped,
    Daniel

  • Base Class NI View Fails

    Hi
    I am currently trying to leverage of my existing codebase by creating a Base class View containing common functionality. My goal is to create the Base class in the form of a (MFC) CFormView with an associated dialog resource containing all my NI controls and underlying code. From there I intend to derive further View Classes based on the former. I have tried this and cannot seem to get the Base class to recognise its members,i.e the Ni controls, whilst the view displays fine and I can see all the Ni controls on form derived from the Base class I cannot execute any of the base class meber functions that need a reference to the Ni controls. If you could give me an example of a project that derives it view from a Base class with ActiveX contro
    ls in it I would be very appreciative.....
    Regards

    I was going to investigate it a little before posting, but
    I'm not sure I can go any further on my own.
    I am using the Yahoo Astra Flash Components. When I add a
    Tree component, and give it a dataProvider that does not use any
    nested nodes, it gives me the error. If I use even 1 nested node,
    then it works correctly.
    I am assuming that the error is stemming from the Yahoo
    Component somewhere, just need to run down what is causing it.

  • Base Class vs Class in the linkage panel

    I have 2 dozen movie clips in the libarary that are all the same structure, but with different content, and I wanted to write a single class that would work for all of them. Popping this in as the base class worked great until I wanted to pass in some arguments to the constructor. Suddenly, it seems I have to write a "shell" class for each asset that contains nothing but super(arg1,arg2) in its constructor (all 24 of them - ugh!). This ends up being really clunky. Is there any way around it?
    Also - in discussing this with a colleague, an issue came up about the exact relationship between the items in the Class and Base Class fields in the linakge panel for a library asset. What exactly is therelationship? Does the class always extend the base class, or is there something else going on?

    undo whatever you did that caused that problem.  you probably assigned a class name that matched one of your base classes.

  • Base class vs derived class

    We have entity classes that we use to access our database. We have subclasses derived from these entity classes that apply business rules. For instance, the base class AddressEntity has a
    setAddress2(string) that AddressEntity.select() uses to set a class variable with data retrieved from the database. The derived class Address also has a setAddress2(string) method that puts restrictions on the length of the data. I want the AddressEntity.select() method to use the base class method AddressEntity.setAddress2(). I've tried using this.setAddress2() in AddressEntity.select() but the derived class method is still used. Any suggestions?
    Thanks,
    Joe

    If you need to call some methods on the base class sometimes and some methods on the derived class other times, but using the same object, then yes dubwai is right you should revisit your Object hierarchy.
    One simple way to do what you are asking is to have your method(s) look like this:
    void setAddress2(String sAddress) { setAddress2(sAddress, true); }
    void setAddress2(String sAddress, boolean bRestrictLength) {
      // real method
    }then you could just look at the variable bRestrictLength to see if you need to restrict the length, and have it default to true. In this way you can use overloading to solve your problem.

  • How to use reflection to get base classes protected field

    I have one base Base classes which have protected fields and public get method to get the field.
    class Base
    protected int proField;
    public int getProField(){return proField;}
    Class Derive extends base class Base
    class Derive extends Base implements OtherInterface
    public void funtion(){};
    Now I have an instance of Derive, how can I use reflection to get the protected field inherited from Base. It seems Java Reflection only give runtime accessibility to public field and decleared field, protected-inherited field is excluded.
    Thanks
    Lei

    as the last poster said, traverse up the class hierarchy.
    ex:
    private void doSumfinToField(String fieldName throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
    Class clazz = getClass();
    Field field = findFieldInClass(clazz, fieldName);
    //field.doSumfin;
    private Field findFieldInClass(Class clazz, String fieldName) throws NoSuchFieldException {
    try { // to find the field in this class    
    return clazz.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
    // if we don't have a superclass, continue
    if (clazz.getSuperclass().equals(Object.class)) {
    throw e;
    // check in the superclass
    return findFieldInClass(clazz.getSuperclass(), fieldName);
    }

  • Warning :: Derived class hides the base class virtual function

    We are porting from CC5.3 to CC5.8 compiler with Sun Studio one compiler. After plenty of hurdles we are in the final stage of removing the warning messages... Amoung the plenty the following one is very common and in different files. Why am I getting this error in 5.8 and not in 5.3 compiler....
    Warning: derived_Object::markRead Hides the virtual function base_Object::markRead(ut_SourceCodeLocation&) const in a virtual base
    From this it is easily understandable that the base class mark read was hidden by derived class markRead... when we drive and override the derived class function.... It is all over the place....
    Thank you,
    Saravanan Kannan
    //public: using xx_Object :: markRead;
    virtual void markRead() const;

    The Sun C++ FAQ discusses the warning message:
    http://developers.sun.com/prodtech/cc/documentation/ss11/mr/READMEs/c++_faq.html#Coding1
    Notice that warnings are not necessarily errors. But I applaud your desire to fix the code so that it generates no warnings. I wish more of our customers could be persuaded to do the same. :-)
    C++ 5.3 issues this warning, by the way. Example:
    struct B { virtual int foo(int); };
    struct D : B { virtual int foo(double); }; // line 2
    D d;
    line 2: Warning: D::foo hides the virtual function B::foo(int).
    If for your particular code you do not see a warning with C++ 5.3, it would be due to a bug in C++ 5.3 that was later fixed.

Maybe you are looking for