Discover my child class

Gurus,
One which may violate OOP, but is useful nonetheless.
Is there currently any way to discover the class of the child through which a parent static method has been called? Here is an example.
I decide to implement many beans that are persistent. I prefer to move the common code, i.e. the persistence, into a single class, have it be the abstract parent, and have all the beans be children of it.
Thus, I may have the following:
public abstract class Parent {
  //lots of common code
public class ChildBean1 extends Parent {
  // Child1 specific code
}For the parent to implement the persistence, I would have the Parent do this.getClass() in its non-static methods (e.g. store() or persist()), introspect the bean, get the fields, and save the data. Easy.
The problem is what to do for finder and other static methods. I would want the Parent to implement them:
  public static Parent findOneBean(args) {
  }Thus, the user of the class would call:
ChildBean1 cb1 = ChildBean1.findOneBean(args1);
ChildBean2 cb2 = ChildBean2.findOneBean(args2);
..The problem is that unlike in the instance case, in the static case, the parent has no way of knowing which Class to Introspect and thus cannot tell anything about the Bean. I tried looking at the stack trace - no go. There is no "this" to speak of.
Is there any way to find out from the Parent? Should I submit an RFE?
Thanks.

Which makes sense to me. The only problem is back to
the original: there does not appear to be a way for
the method to find its own class. Even if there was, this could only determine the class in which the method is defined, not the calling class (which in your example just happens to be a subclass, but in general doesn't have to be).
Determining the class of the object/class which calls a method is already part of the StackTraceElement API.
Truth is, this is a general problem: a static method
really has no way of saying "give me my Class" the way
a non-static method can say this.getClass(), does it?True. But the equivalent of 'getClass()' would not return the class of the caller, which is what your example requires.
this.getClass() does the right thing, wherever it is called.It returns the class of the callee not the caller. This would not be the right thing in your class, as the class of the method would always be the superclass.
So what you're asking for is static methods to get the caller's class (in you case the specialized bean), but non-static methods to get the callee's class, such that:class A {
  static void foo {
    System.out.println(Thread.getCallerClass());
  static bar {
    System.out.println(this.getClass());
class B {
  static void main (String[] args) {
    A.foo();
    new A().bar();
    System.out.println(Thread.getCallerClass());
class C extends A {
  static void main (String[] args) {
    A.foo();
    new A().bar();
    System.out.println(Thread.getCallerClass());
}So, running B would print outB.class
A.class
some JVM loader classAnd running C would print outC.class
A.class
some JVM loader classI'm not sure that it's in any way useful. It certainly doen't correspond the getClass method.
Why do you need it anyway? If you cannot deduce what needs to be serialized from the type of the arguments to your static serialize method, then there is something wrong in the parameters. If it is, for example, the same data, but a subclass specific header, then have the subclass declare an abstract method that returns the header content.
Pete

Similar Messages

  • Class override, how to create the child class and then the base class

    I started to write a program for a smart DMM, the problem is every version of the DMM the company change the communication commend.
    My idea is to write a child class for every DMM version and every SubVI of the child will override the base class SubVI.
    My problem is, i want first to create one child class and after i will see every thing is work,  start to create the base class. that way i will see if am thinking the right way.
    My question is
    How can i create a child class and then create the base class and configure the SubVi of the child class to be Override of the base class?
    I tried to search in the property of the class but i didn't see nothing.
    Thanks
    Solved!
    Go to Solution.

    This can be done and I've done it on occasion.
    You simply create the base class with the dynamic dispatch methods you require (connector panes need to be identical to thos of the child class).
    Then set the inheritance of the class to inherit from this base class.  If your method is defined as a dynamic dispatch method in the parent, you'll most likely now have some errors (unless your child method was already DD in which case you might just be OK already).
    To change the inheritance of a class, right-click the properties of the class in your project and select properties.  I believe the ineritance tree is at the lower end of the properties.  Click on the "change inheritance" (or something similar) to choose the class from which you now wish to inherit.
    Say hello to my little friend.
    RFC 2323 FHE-Compliant

  • A non abstract child class must implement all pure virtual function of  parent abstract class in c++

    Hi,
    In Indesign SDK there is a class  IActionComponent having two pure virtual functions:
    virtual void
    UpdateActionStates(IActiveContext* ac, IActionStateList *listToUpdateGSysPoint mousePoint = kInvalidMousePoint, IPMUnknown* widget = nil) = 0;
    virtual void
    DoAction(IActiveContext* ac, ActionID actionID, GSysPoint mousePoint = kInvalidMousePoint, IPMUnknown* widget = nil)= 0;
    But, the child class
    class WIDGET_DECL CActionComponent : public IActionComponent
    implements only UpdateActionStates function and not DoAction function.
    There is no compilation error and the code is running fine..HOW
    Can some one please explain me?

    Oops!!! there is a small correction in my C++ program. The JunkMethod is being called from the constructor...like the following code.
    #include <iostream.h>
    #include <stdlib.h>
    class Base
        public:
            Base()
                cout<<"In Base Class constructor..."<<endl;
                JunkMethod();
            void JunkMethod()
                TestAbsFunc();
            virtual void TestAbsFunc()= 0;
    class TestAbstract:public Base
        public:
            TestAbstract()
                cout<<"In Extend Class constructor..."<<endl;
            void TestAbsFunc()
                cout<<"In TestAbsFunc...."<<endl;
    int main()
          TestAbstract test;
          return 0;
    }You can see the change in the constructor of the Base class. JunkMethod is being called, just to bluff the compiler to call the virtual method (so that it won't crib saying that abstract method cannot be called from the constructor). When Java is supporting this functionality without giving any errors, C++ gives errors when you call an abstract method from the constructor or fails to execute when I do some work around like this. Isn't it a drawback of abstract funcationality supported by C++ (I'm not sure if it's a drawback or not)
    Regards,
    Kalyan.

  • Fastest way to create child class from parent?

    As the subject states, what do you folks find is fastest when creating child classes directly from the parent? (esp. when the parent is in a lvlib) I thought I'd post up and ask because the fastest way I've found to get working takes a few steps.
    Any suggestions ae appreciatized!
    -pat

    Thanks for the quick response Ben!
    Yea, I apologize, in your response I realize my OP was more than vague haha (it hapens when you get used to your own way of doing things I guess huh)- I'm trying to create a child from a parent so that it has all of the methods that the parent has.
    In order to do so I currently have to open and close LV a few times during my current process so that vi's in memory dont get mixed up- Currently I save a copy of the parent class in a sub dir of where it is saved, close out of LV, open the new 'copy of parent.lvclass', save as>>rename 'child class.lvclass', close LV, and open up the project to 'add file', then right click>>properties>>inheritance.
    Is this the only way to do this?
    Thanks again!
    -pat
    p.s. I'm tempted to steal your cell phone sig, hope you dont mind haha good stuff!

  • How to get the child class in inheritance?

    hi,
    if I have a store for renting videos .. and I have Video class (parent) and two (child) classes DVD and Cassete which they are extend the video class.
    And the user wants to rent a DVD which is the child, how do I do that? can I write just getDVD() as simple as that or maybe I need to use a keyword like "getinstance of DVD " or something I don't know how to do this.
    class Video have attributes like title, date of production and director.
    I'm not good in inheritance help please.
    thanks

    georgemc wrote:
    DrLaszloJamf wrote:
    Post a SSCCE: http://mindprod.com/jgloss/sscce.html
    You're not the boss of me ;-)Actually, I haven't stopped to count, but most of the time the poster never bothers to write a sample program. If fact, if I weren't such a softie, I would make that an absolute requirement for any further help. Too often, you are just shooting in the dark and 50 replies later the question is still vague.

  • Setting final Instance variables in Child Classes

    Hello:
    Is it possible to declare (not initialize) a final variable in an abstract parent class and set it in a non-abstract child class.
    An example for clarification.
    I have an abstract parent class (call it P) and two child classes (call them (C1 and C2). There is common processing that goes on in P. This processing uses a variable called x. C1 will set x to equal 10 and C2 will set x to equal 20. Can I declare x final in the abstract class P and set it in C1 and C2
    This is impossible right? I know some other languages allow this behavior so I just wanted to make sure that Java does not support it.
    Thanks
    Johnny

    Why don't you just try it out? Though I'm pretty sure it won't work, as it should expect all constructors of the abstract class to set it. But you could either let there be an overridden method that returns the appropriate value for the sub-class:
    abstract class P
      abstract protected int getTheValue();
    class C1 extends P
      protected int getTheValue() { return 10; }
    class C2 extends P
      protected int getTheValue() { return 20; }
    }

  • Easy One: Constructor of Child Classes

    Hello. I am new to the java language and i have a question.
    I want to make a Class Vehicle which should have the following variables
    static int id;
    static long color;
    static String brand;
    static Boolean rented;
    static String location;
    Now i want to make a Child class called 'Car' which should have the .location set to "land" by default.
    I want to also make a Child class of 'Car' called 'Bus' .
    Now the problem is with the constructors. I want that when i create a class Bus that the .location is set to "land" automatically and not with user input. This means it will call the constructor of 'Car' and not 'Vehicle' which sets .location to "land"
    I tried to do so but it tells me 'Constructor Car() was not found' .
    I want the constructor of Car define the .location="land" but the constructor of Bus will not have the .location argument because
    it is set to "land" by default?
    Please help !
    thanks
    code follows:
    package map_exercise;
    * Title:
    * Description:
    * Copyright: Copyright (c) 2003
    * Company:
    * @author
    * @version 1.0
    public class Vehicle {
    static int id;
    static long color;
    static String brand;
    static Boolean rented;
    static String location;
    public Vehicle(int myid,long mycolor,String mybrand,Boolean isrented,String mylocation) {
    this.id=myid;
    this.color=mycolor;
    this.brand=mybrand;
    this.rented=isrented;
    this.location=mylocation;
    package map_exercise;
    * Title:
    * Description:
    * Copyright: Copyright (c) 2003
    * Company:
    * @author
    * @version 1.0
    public class Car extends Vehicle {
    public Car(int myid,long mycolor,String mybrand,Boolean isrented) {
    super(myid,mycolor,mybrand,isrented,"land");
    package map_exercise;
    * Title:
    * Description:
    * Copyright: Copyright (c) 2003
    * Company:
    * @author
    * @version 1.0
    public class Bus extends Car {
    public Bus(int myid,long mycolor,String mybrand,Boolean isrented) {
    }

    I agree with NadjaS about the general remarks on the use of static vs. instance variables.
    Anyway, if you really need to keep the variables at the class definition level, you can initialize them through the static initializer constructor within the "Car" class itself, i.e. something like this:
    public class Car extends Vehicle {
        static {
            location = "land";
    }without necessarily calling the super constructor.
    The message "Constructor Car() was not found" is due to the fact the the only Car class constructor has four parameters - hence a completely different signature - and there is no constructor without parameters at all.
    Hope this will help.
    Bye

  • Casting parent class to a child class

    Hi,
    I have a static method which returns a class called parent. Now I want to cast it it's child class. There are no compilation errors, but at runtime it's throwing me ClassCastException. This is what I'm doing.
    public Parent getObject() {
    Parent p = new Parent();
    return p;
    Child c = (Child) getObject();What is wrong with this code? I couldn't figure it out.
    Any help will be appreciated.
    Thanks,

    Parent p1 = new Parent(); // 1
    Parent p2 = new Child(); // 2
    Child c1 = new Parent(); // 3
    Child c2 = new Child(); // 4
    Parent p1 = (Parent)c1; // 5
    Parnet p2 = (Parent)c2; // 6
    Child c3 = (Child)p1; // 7
    Child c4 = (Child)p2; // 81: Ok.
    2: Ok. Every Child IS-A parent.
    3: Compile time error. A Parent object is not a Child.
    4: Ok.
    5: Ok, because every Child IS-A parent, and the cast is unnecessary. (Though since 3 is illegal a compile time we wouldn't actually have this situation.)
    6: Ok, and the cast is unnecessary, because every Child IS-A Parent.
    7: ClassCastException at runtime. The object is not a Child.
    8: Ok.

  • Copy multiple dispatch vi to new child class

    Hi, I have just started with LVOOP and while I'm pretty sure I have a good understanding of the overall theme, there is one problem I foresee if I continue.
    Situation:
    BoardType is parent of classes CC2600 and CC1300. Currently the child classes are just empty place holders.
    Almost all the methods in the child classes will be of dynamic dispatch type (currently only one).
    From what I understand a dynamic dispatch must be available in all child classes plus parent class in order to work as intended. 
    Problem:
    If I would go forward and implementing LVOOP this would require approx 30 dynamic dispatch vis for each class. I can right click but for just these two children that's 60 + 30 vis I must create manually. I would much prefer just to create a template once and then just basically drag and drop 30+ new vis for each new class that is created.
    Is there a way I can define a set of template dispatch vis in the parent BoardType and have them added to all the child classes? 
    I tried the save as copy, but the problem is that I still have to replace the connector pane to represent the new owning class.
    If it helps here's a very basic block diagram of what's going to happen, just after Reset.vi there will be a lot of other dynamic dispatch vis.
    Thanks in advance.
    Michael

    From the OP it sounded like you were literally just copying from the parent.
    What I tend to do is finish one child class and then save a copy to a new name and change the internal data (if required) and DD vis (if required).
    I do agree though that these kinds of operations could be hugely simplified using helper programs.  Give the link provided by others a try.
    Shane.
    Say hello to my little friend.
    RFC 2323 FHE-Compliant

  • Preventing Child Class Dependency when using conditional disable to specify Class in Development Environment

    Hello
    I am developing an application which I would like to execute on both normal and real-time systems using LabVIEW Proffesional Development System 2012 SP1
    To control how the application interacts with the user, I have created a class which defines the type of user-interface behaviour which should allow me to have nice dialog boxes when the system is executing on a windows machine and have no dialog boxes (or other non-Real-Time friendly code) when operating on a real-time target.
    The parent class is the code that is suitable for Real-Time and the child class is the one with dialog boxes.
    To control which class is loaded, I have a conditional disable structure. This will work fine when the application is built into a executable or real-time executable but the problem arises when I want to use the code during development on the real-time target.
    I find that with the application under a real-time target (RT PXI), the correct conditional-disable case is activated so the parent class is used, but the child classes are also listed under the dependancies - I pressume this is because they exist on the block diagram in the disabled case of the conditional disable diagram.
    This means that I cannot deploy the code to the Real-Time target as it is unhappy with the child class code - even though this will never be run.
    To save posting my real project, I have created an example with a Parent and Child class and a Conditional Disable Flag called "CLASS" to demonstrate the problem.
    If you run Test.vi you will see that the Child class still gets locked (i.e. is a dependancy) during execution even though it is not called.
    So - basically my question is: Is there anything I can do about this or will I just have to do-away with the conditional disable and just put the correct Class constant on the block diagram during testing?
    Thanks in advance
    John.
    Solved!
    Go to Solution.
    Attachments:
    Example Proj.zip ‏18 KB

    I feel your pain.  I ran into a similar problem a short time back.
    Apparently Official NI stance is that you need to put a conditional Disable structure IN EVERY ONE OF YOUR CLASS VIs.  In the Windows VIs, you simply have an empty conditional disable case with the windows code in an appropriate other case and vise versa on the RT.
    I too would much prefer the method you describe...
    Say hello to my little friend.
    RFC 2323 FHE-Compliant

  • Executing a child class from parent.

    Hi, well, I have this parent class which I need to execute a method from a child class to get a significant part of the thing get started. Is there anyway for me to accomplish this or a workabout? Thanks..

    Sure.. I have this method in the class logic:
         public void createLocation() {
              try {
              classCoord coordSet = appinterface.decodeFile();
              int areaNum = coordSet.areaNum, cellNum = coordSet.cellNum, signalStrength = coordSet.signalStrength, receiverId = coordSet.receiverId;
              String dateTime = coordSet.dateTime, userName = coordSet.userName, location = calLocation(areaNum, cellNum);
              boolean validity=calValidity(signalStrength);
              classLocation locationObj = new classLocation(this.type, userName, receiverId, validity, location, dateTime);
              appinterface storeLocationObj = new appinterface();
              storeLocationObj.storeLocation(locationObj);
              catch (IOException ioException) {
                   appinterface.displayMessage("Logic Error: " + ioException);
              catch (ClassNotFoundException classNotFoundException) {
                   appinterface.displayMessage("Logic Error: " + classNotFoundException);
         }I need to execute this method halfway in the class appinterface, the logic class inherits from appinterface cuz I need to make use several methods from it. Is there any way to solve this somehow?

  • How to listen to user actions in child class from parent class?

    Hi,
    I have a basic custom class ChildCustomForm that include a JTextField. In order to know what user types, I add a listener to
    this textbox:
    textField.addKeyListener( new KeyAdapter()
                @Override
                public void keyPressed( final KeyEvent e )
                    //user typed something
                    userTyped = true;
             });Now I have another parent class that uses ChildCustomForm, and parent class has to know once user types, then set
    its own userTyped flag.
    My problem is: since I added listener in child class, I cannot get textfield and add listener again in parent class, so parent class will not be able to know as soon as user types (polling is not a good solution here).
    I am wondering if there is a way to do this?
    regards,

    jack_wns wrote:
    I have a basic custom class ChildCustomForm that include a JTextField. In order to know what user types, I add a listener to
    this textbox:You want to listen for input into the textbox, correct? This may take the form of keyboard input, or could be a paste-text event in which case your keylistener will miss it. I recommend that you look into a DocumentListener here so you will catch any changes, be they keyboard or cut or paste.
    My problem is: since I added listener in child class, I cannot get textfield and add listener again in parent class, so parent class will not be able to know as soon as user types (polling is not a good solution here).The observer pattern may work here.

  • How to reduce protected accessor to package accessor in child class

    I have made one abstract class ( say Parent), with 2 abstract methods (am1() & am2()) , with protected accessors. A class extends parent class (say Child). Now Child class need to keep accessors type of protected method as protected, as we cannot reduce the scope. Now as per my design, I need to create many subsclass (say SubClass) of Child class. But I don't want subclass of Child class to have access of method am1() & am2(). SubClass is declared in different package. But as I cannot reduce the accessor type from protected to package, I am not able to restrict the access of am1() & am2() to Child class and SubClass should not able to access am1() & am2().
    Do we have some way to design above scenario?
    Thanks in advance
    Praveen

    You can't reduce visibility.
    A subclass is supposed to be able to do everything the superclass can. If you'd restrict visibility of certain methods or fields, you break that contract.

  • Seemingly unpredictable results when calling an overriden parent method on an instance of a child class casted to the parent class

    I have a parent class with a sub-vi Override.vi, and a child which overrides this sub-vi.  I create an instance of this child.  I cast this child to it's parent class and store it in an array.  Later, if I invoke the parent's 'Override.vi' on this child (casted to parent) then Labview 2013 seems to randomly choose whether to run the parent or the child override.vi.  In Labview 2011 SP1 it would always call the childs version of override.vi (which while surprising to me was very useful).  This has totally broken an application I have been developing, any insight as to how to control which override.vi is run would be helpful (re-casting to the child class isn't really an option, as there are in fact many child classes each with their own version of override.vi).

    The actual data type of the wire is irrelevant in deciding which VI to run. The only thing that is relevant is the class of the object which is actually on the wire, so casting to the parent should not be relevant. *IF* the object really is a child, then LV should always call the child's VI, just like you say it works in 2011.
    I suspect that what's happening in your case is that somewhere you're generating a parent and that's what's actually on the wire (e.g. maybe you have an error somewhere and a function outputs the default value, which is a parent). The fact that it didn't happen in 2011 doesn't mean it's a bug in 2013. It could be that something else has changed.
    In any case, it's impossible to tell whether this is a misunderstanding, a bug in your code or a bug in LV without actual code. If you can post actual code which shows this, people can help. Otherwise (if it only happens in code you don't want to publish), you should try contacting NI directly so that you can at least show them the code.
    Try to take over the world!

  • Parent class not waiting for child class to finish

    hi,
    i have class a and method x in class a which calls class b. its fine till there. but before my class b's action is completed, in which i have to choose a file and display those files in jtable, the remaining lines in method x getting executed. what do you think the problem is.
    i.e. my parent's class method is completely getting executed before the child class (frame) returns the result and is closed. where do u think the problem.
    please help.

    i dont know if i made myself clear. i am giving my code below.
    class A{
    btnClick{
    pnlProductsImport _pnlProductsImport=new  pnlProductsImport(dataSource,config,parent,importFile);
    _pnlProductsImport.setVisible(true);
    _pnlProductsImport.show();
    getProducts()
    here its showing my pnlProductsImport class screen and before I close that screen, getProducts method is getting executed. as I know, the control passes from class A to pnlProductsImport at show() and when its closed, it will execute remaning lines i.e getProducts, but in this case, it shows the subclass, and immedietly, executing remaining lines. but its also fact that my subclass (pnlProductsImport) implements Runnable, but thread starts only after some time when I click on one of the buttons on the screen.... and i want that getProducts() method to execute only when subclass closes completely.
    thanks

Maybe you are looking for

  • OneKey Recovery broke after reinstall with retail DVD

    So I know this has been an issue (After reading tons of posts after the fact...) but couldnt find a straight clear resolution for my situation or I missed it somehow. Anyway got a G530/3000 4446-23U. Came with Vista Home Basic and the OKR button thin

  • How to get rid of quotes in copied hyperlinks?

    I'm using Numbers to keep my hyperlinks, and suddenly discovered that it brakes them when I try to copy-paste them anywhere outside from Numbers. For example, link in cell looks like: (a href="link")link tex(/a) Note: symbols < and > are replaced wit

  • HP Compaq d330 uT d330m/P2.8C/40bc/128F/4

    Dear Sirs, We are getting message INPUT NOT SUPPORTED on the display Kindly advice why we are getting message INPUT NOT SUPPORTED, IN CASE IT IS IS BECAUSE OF DRIVER FOR VIDEO, request to let us have the driver S/N of CPU[edited by Moderator], P/N  P

  • Not reconizing songs!

    my ipod is reconized in itunes but the songs and apps aren't! i can't sync it with out losing all my data!

  • Error message when running editable alv

    Hi all, I hava a problem with an editable ALV. I created it with the following method wddoinit: METHOD wddoinit . initialize ALV Component   DATA: l_ref_cmp_usage TYPE REF TO if_wd_component_usage.   l_ref_cmp_usage = wd_this->wd_cpuse_alv( ).   IF l