To access the class fields in another package (reflection)

Hello

Given that I have not found a section named "Reflection" in the forums, I guessed that this would be the place to post my question.

I'm trying to implement a function called setField (field, value) in my classes using reflection. I have included this function in a base class so that its child classes could also use this feature.

The base class looks like:
public class Base {

    private Integer x;

    public void setField( String fieldName, Object value) {
        Class cls = this.getClass();
        
        while (cls.getSuperclass() != null) {
            System.out.println(cls.getName());
            
            try {
                Field field = cls.getDeclaredField(fieldName);
                field.set(this, value);
                break;
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(JPT.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(JPT.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchFieldException ex) {
                Logger.getLogger(JPT.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SecurityException ex) {
                Logger.getLogger(JPT.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            // if field not found in this class, check the superclass
            cls = cls.getSuperclass();
        }
    }
    
    public Integer getX() {
        return x;
    }

    public void setX(Integer x) {
        this.x = x;
    }
}
And then I have a class of the child:
public class Child extends Base {

    protected Integer y;

    public Integer getY() {
        return y;
    }

    public void setY(Integer y) {
        this.y = y;
    }
}
So, basically, I need to get the type of features to work, i.e. to change a field in the child's class using the function available from the following base class:
Child child = new Child();

child.setField("y", new Integer(20));

System.out.println(child.getY());
This works when the base so the child classes are in the same package, but when they are on different packages, I get an error that looks like:
java.lang.IllegalAccessException: Class teletutor.core.test1.Base can not access a member of class teletutor.core.test2.Child with modifiers "protected"
     at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:95)
     at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:261)
     at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:253)
     at java.lang.reflect.Field.doSecurityCheck(Field.java:983)
     at java.lang.reflect.Field.getFieldAccessor(Field.java:927)
     at java.lang.reflect.Field.set(Field.java:680)
     at teletutor.core.test1.Base.setField(JPT.java:27)
I hope that I have identified my problem. Please suggest how I can get the desired effect.

Thanks in advance.
field.setAccessible(true);

Tags: Oracle

Similar Questions

  • ACCESS the same table in another file gives message as there is no...

    I'm working on a little game of shooting like a project to learn as3.

    I struggled a lot with the as3 syntax, but am willing to grit your teeth and hope that someday that light...

    the problem:

    I created three clips in a fla.

    I plugged 4 .as files to the fla:

    Bomber.As

    Bullet.As

    Kanon.As

    Shooter.As (connected to the phase of files / himself).

    All the behaviors of the mc are described in packages in their own connected .as file.

    I want to do a hitTestObject with "chips" and "bomber".


    as file f the ball inside, I make a table to store the bullets.


    When I want to access the same table in another .as file, I get a message there is no...


    Can anyone suggest a solution...?

    any help is very appreciated!

    If the bullet.as file is supposed to be for a ball, and you intend to have more than one ball in action at any given time, so you probably don't want this table in the class bullet.as in any case.  If the shooter file is the actual game file, then I have the file of shooting game in charge of the creation of new instances of the ball, and that is where I keep track of them in a table and their test against the bombers.

  • To access the classes of CPP in qml.

    I have set up to access the classes of PCB in qml in two ways: -.

    1. create an attached object and the id of the class of CPP special and then access via the id.

    2. fix the CPP on the qml class before pushing the page using the setContextProperty.

    I wanted to know exactly when to use these two methods. There a difference in terms of scope and memory. Please explain.

    Great Question!

    Local objects:

    Attached to objects, or who inherit from classes of cascades, is the simplest way to expose c ++ objects that relate to user interface elements. This is what you use if you want this object to BELONG to this context qml. It is created by the qml context when createObject is called (your qml file is loaded) and destroyed with the user interface objects. You can create many of these objects, anywhere you need. However, if you want to expose global properties, it is probably not a good approach.

    The only time you would use objects attached to global stuff is if you expose a singleton class to allow qml set locations to manage signals (OrientationHandler is an example of that, without an OrientationHandler object, that you have nothing to connect).

    Global objects:

    Context properties can be considered global variables for a particular context, but with inheritance: context properties are passed to the contexts of the child. These objects are the PROPERTY of c ++, must be created before the creation of the object (createObject is called) and must remain valid for the lifetime of any context, they are placed in, but then destroyed is no longer necessary.

    The disadvantage of context properties changing them can be expensive. If you set a context property after the createObject call (that is to say an object exists that was created from this context), then all links in javascript in this context will be re-evaluated. However, you can mitigate this issue by exposing an object that contains the value as a property, so that links to branch on change of signals well if necessary.

    Inheritance is where shine context properties. There is a context root, which is in this context of default parent for new contexts. If you set a context property of the root context, it is available everywhere in any document qml. Here is an example of how do:

    QmlDocument::defaultDeclarativeEngine()->rootContext()->setContextProperty("app", myApp);
    

    Note: when I speak of createObject, I'm talking about QDeclarativeContext::createObject. It is called internally by QmlDocument::createRootObject.

    For more information on the Qml contexts, see http://qt-project.org/doc/qt-4.8/qdeclarativecontext.html

    For more information about the inner workings of qtdeclarative, see http://qt-project.org/doc/qt-4.8/qdeclarativeengine.html and http://qt-project.org/doc/qt-4.8/qdeclarativecomponent.html

    http://Qt-project.org/doc/Qt-4.8/qtbinding.html is still relevant as well

  • Question: How do I assign a TOKEN for the class, field, method in the export file?

    Hi all

    Please take a look at this photo: http://www.flickr.com/photos/25615172@N08/5788551711

    I have a question for you:

    1 / in the export file, what allocation rule of tokens for the classes, fields, methods?

    2 / how, the articulation between * #token_c2.token_f2* and public-> field3 protected class3 ?

    3 / how the articulation between * #token_c2.token_m2* and public-> protected method3 class3 ?

    Thank you
    HoaND

    I am interested in this topic as well and looking for the answer elsewhere. Let me know if you have the answer

  • How to access the class of an Actionscript object

    Hello

    I'm trying to access the class of an Actionscript object as the Java method getClass().

    example:

    I have this class with a method "myMethod(clazz:Class)".

    public class Class2
    {
         ... 
         public function myMethod(clazz:Class):void
         {
           ...
         }
    }
    

    This other class:

    public class Class1
    {
        var class2:Class2 = new Class2()
    
        public function otherMethod(obj:Object):void
        {
              class2.myMethod(obj.????);
        }
     }
    

    Perhaps is it not possible?

    Thank you

    vdelbart

    There is no native to retrieve method class of an object, but this utility function should work for you:

    import flash.utils. *.
    import flash.system.ApplicationDomain;

    function getClass(o:*, appDomain:ApplicationDomain=null): Class
    {
    If (o == null | is a class o) {return o ;}

    result: var class = null;

    Try
    {
    var cName:String = flash.utils.getQualifiedClassName (o);
     
    If (appDomain! = null)
    {
    try {}
    result = appDomain.getDefinition (cName) class;
    }
    catch (err2) {result = null ;}
    }
    If (result is nothing)
    {
    Result = flash.utils.getDefinitionByName (cName) class;
    }
     
    }
    catch (Err) {result = null ;}
    Finally {}
    return the result;
    }

  • Possible to access the listener function in another class?

    I want a listener on a tween on the document class when it is finished, it goes to the listener of its child function, but I don't know how.  I thought it would be just a case of document.functionName, but it is throwing an error.

    I've got:

    treeWidth_tw.addEventListener (TweenEvent.MOTION_FINISH, Bauble.startFade) in the parent document

    and in the mc of the child:

    public void startFade(evnt:TweenEvent) {}

    fadeTween = new Tween(this,"alpha",Regular.easeIn,0,1,3,true)

    }



    I get the error message:

    1061: call to a startFade method maybe not defined through a reference with static type class.

    Is the class trinket or is it and the instance name?

    Generally, class names begin with a capital letter and instance names are tiny. So I guess that bauble is the name of the class.

    In this case Flash expects a static class called startFade method. So to you class file you defined:

    public static void fadeStep()

    or is it defined as an instance method?

  • To access the backups Time Machine another computer

    I have spent a good hour looking for a solution to this problem, but have developed empty-handed.

    If I understand correctly, backups of access from another Mac time Machine, I need to connect the backup drive to another Mac and select "Browse Other Time Machine disks... "in the Time Machine dock menu and choose the drive.

    The backup drive appeared as expected and I clicked on "Use selected Disk" to enter the time Machine.

    At this point, the computer between what seems to be Time machine, but shows a Finder window to the hard disk of the computer rather than the backup drive and shows not all dates before "today (now)."

    A thread has suggested that I open a Finder window and select 'Computer' in the menu to reach before the opening of time Machine. It did not work.

    Another thread has suggested that I have use the Migration Wizard rather to recover files and folders, I need. This is not ideal, but I tried it anyway, the result being that the Migration Wizard app remained "Looking for source...". "without finding the backup drive.

    Before formatting my drive on the original Mac, I had checked for if ensure that I could access the Time Machine backup while it was plugged into the backup drive (which he successful well).

    I use the latest version of El Capitan 10.11.6 on a MacBook Air (mid 2011). Backup is a MacBook Pro (mid-2010) who ran as El Capitan.

    I would appreciate any other suggestions!

    So, I discovered the solution, which has been in a simpler way that I expected. Before opening, Time Machine, it is necessary to find the sparsebundle Disk Image in the backup disk in the Finder and open it with "DiskImageMounter." Then, you must select "Computer" in the Finder menu reach before choosing the option "Browse Other Time Machine disks... "menu to the dock of time Machine. The first finder window it shows in the Time Machine view still belongs to the computer, but now it shows the previous backups, who are all from the backup drive!

  • To access the EFS data from another disk using original certificates/keys

    I use EFS on a Workgroup XP - Pro, SP3 and have backed up keys.  I am trying to access the files on this disk now mounted in another machine (also SP3 of XP - Pro and in a working group).  I can load the certificates of the first machine in the second machine by double clicking it.  Once the certificates are loaded, how decipher you?  I get "Access denied" when I right click and try to decrypt the files on the original drive.  The MS help talk about designating a "File Recovery Agent", but this procedure seems to be to area of machines and gets a bit fuzzy for working groups.  BTW, I'm testing my file recovery process.  No data is at risk.  Can you tell me FAQ to decrypt a file on a disk that is moved to another machine using the original (REC & PFX files) encryption certificates/keys?

    Hello Stephen,

    The question you posted would be better suited for COMPUTING public Pro on TechNet. I would recommend posting your query in the TechNet Forums to get help:

    Windows XP TechNet forums

  • To access the form field values

    Hi all

    I have a form with several fields. I need to change the value of a field as 'Y' and send the form in the java code.
    I used the following
    FacesContext fctx = FacesContext.getCurrentInstance ();
    RichInputText = (RichInputText) fctx.getViewRoot (.findComponent("pt1:r1:Active1")) active1;
    If (active1. GetValue(). ToString(). Equals("Y"))
    active1. SetValue ("N");
    on the other
    active1. SetValue("Y");
    This changes the value, but if I run "Commit" operation using
    bindings.getOperationBinding("Commit").execute ();
    its not saving in dB.

    My usecase:
    By clicking on the button, need to change the value of the indicator (field) and submit the form that has to go to DB.

    Please suggest me the right way.

    Concerning
    Suresh Camille

    can you explain your case to use a little?
    Your first message, I understand you want to access the value of Active1
    You can use this code:

    // get the binding container
    BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
    
    // get an ADF attributevalue from the ADF page definitions
    AttributeBinding attr = (AttributeBinding)bindings.getControlBinding("test");
    //set the val
    attr.setInputValue("newval");
    //get the val
    String val = (String)attr.getInputValue();
    

    your second post, I see that you are editing the text. So I'm a bit confused.

    Timo

  • Access the class from the loaded module

    I have this in the main application and I the public variable test in the module. The problem is that I don't know how to access it properly.

    public

    var fontsModule:IModuleInfo;

    public var FontsClass: Class;

    public

    function initApp(evt:FlexEvent):Sub

    {

    fontsModule = ModuleManager.getModule ("modules/fontsBG.swf");

    fontsModule.addEventListener (ModuleEvent.READY, fontsLoaded);

    () fontsModule.load

    new ApplicationDomain (ApplicationDomain.currentDomain), null , null , moduleFactory);

    }

    public function fontsLoaded(evt:ModuleEvent):Sub

    {

    FontsClass = fontsModule.factory.create)

    as Class;

              trace ()' HERE: "(+ FontsClass.test);". "

    }

    If I replace the class with the name of the 'FontsBG' class actions script in this example, everything would work, but the main swf file size goes from 100 to nearly 400 kbs when the fontsBG.swf file is 67 kbs. So I'm certainly not doing it right.

    So the question is: what is the correct way of loading the modules and using their properties and functions - through the class or interface and how it's done? Please set up a small code example so I can get the concept of base as well as the readers of this thread.

    Thank you!!!

    (3) again, you will need to use a shared interface or a common base class.

    Most people put the UI widgets in a module and they all extends UIComponent

    You can reference them as UIComponents.  If they need to access other

    Properties and methods, they define an interface.

    (1) my guess is that the button does not know what a module with embedded

    fonts loaded and don't refresh to use.  Normally, you would

    wrap styles in the module with the fonts, and then set styleonce

    the module is loaded.  In this case, you specify MyriadPro as the

    CSS font family and he would set via setStyle once the module is loaded.

  • The exact text of the text field to another field read-only

    Is there a way to display the string of exact text in the field of text within other text fields read-only?

    For example. I have fields of name on the first page and I have the same names mentioned in the other pages, but want to fill the other pages with the text name of the 1st page.


    Options tab > Default value doesn't seem to work, so maybe I can use calculate tab > simplified field notation.

    I have a domain called "Client_1_Name_Cover" and "Client_2_Name_Cover", so name to bind these two text fields only reading on other pages.

    You can use the validation script custom following in each of the two fields of name on the first page:

    Copy the value of this field in the field read-only

    getField("Client_1_Name_Readonly").value = event.value;

    but you must replace 'Client_1_Name_Readonly' with the actual name of the field read-only.

  • To access the properties of the class one from another

    Hello

    I have two clips on the stage at frame 1 and frame 2. Both are instances of classes. (They are not created dynamically, just their affair is set to their class names)

    I created soundChannel and sound objects in class 1 and I want to access it from class 2. (I want to stop the sound chain that was started in class 1)

    Is it possible to do this? If so, this will be true for other properties also?

    Thanking you,

    Chinmaya

    You want to stop the sound of the previous movieclip, right?

    You can do this by using SoundMixer.stopAll ();

    It stops all sounds in your SWF file. You can also start any sound later.

    The second approach is to do your "musicChannel' a global variable.

    To do that he report on a new layer which is empty and avialbale throughout the main time line and without pictures keys are there [with the exception of the first presence].

    now to access this variable, you can use a statement like below:

    (stage as MovieClip).musicChannel.stop ();

    If that also does not solve your problem then paste the code for the two classes, I'll look into it.

  • How do I access the DW site on another computer

    I'm sure that this is possible, but don't know how!

    My laptop is currently being repaired to the Applestore - not open unfortunately.

    During this time, I want to access my site DW to make changes.

    Is it possible to download the remote file and enter the details of the site on another machine.

    Can if yes, please someone talke me as a novice through the SIMPLE procedure -

    Thank you

    Sure...

    1. open DW and choose Site > New

    2. give your site a name and create a folder to hold it in

    3. Enter your FTP info under remote server

    4. in the window of the files in your new blank site, click on the Get (down arrow) button, which will link DW to your site and you prompt to download the whole thing

    5. click on Yes, sit down, relax and wait for your site to download on your machine

  • Copy the contents of the text field to another text field

    Hello world

    I'm new in the world of LiveCycle. Therefore, please excuse these stupid questions (?).

    I'm trying to create a form. This form has three pages at the moment. On the first page, the user must fill a number of services.

    How can display this number of service on the following pages?

    I read something about JavaScript and FormCalc. Is there a manual for beginner? A manual or a good how would be great because I have more question and does not usually bother forum that much. for example, ist is possible to hide a 'Kontrollkastchen' (English control box?), when an another Kontrollkastchen is not checked? Something like a "IF box A THEN not true to hide the B.

    Concerning

    Dennis

    Thorlabs HL

    Hi Dennis,

    Your question is very valid; you know what you want the program to carry out, it isn't just get to do.

    You can do without a script. If you copy the field on every page, you can set the binding to "global". This means that all the fields with the same name of object will have the same value.

    If the object is going to be in the same place on each page, you can place the object on the Master Page.

    Some resources are in this tread: http://forums.adobe.com/thread/427826?tstart=0

    Also have a look at the help file to configure your workspace...

    Good luck

    Niall

  • Access the value of an another file callback function

    I have a callback function, where to get the current value of a control in a main.c.

    GetCtrlVal (panelHandle, PANEL_RINGSLIDE_1, &p);
    

    I have another file (test.c) in the same folder. I need to use the value of & p in the file test.c. How is that possible?

    I have understood #include main.c in the file test.c but not working.

    Any ideas?

    In applications that use multiple source files, it is advisable to have a set of common definitions that covers all of your project. So, for example, you could have a "common.h" file, which is #include'd files test.c both your main.c. In this file common.h, you might have a statement:

    extern int p;

    This indicates to the compiler, for each of your steps in compilation of file c, the variable p is defined somewhere else and do not worry about this. Now, in a few of your .c files (not really matter which), you then have to declare the real variable p:

    int p;

    So now, when you reference an upside in one of your modules, you refer to the same variable across the whole project. (It is probably best to use a longer, more descriptive name for the variable instead of just p - this avoids possible confusion as your program grows in complexity).

    JR

Maybe you are looking for

  • How can I get all internet radio to work again in iTunes?

    I am running iTunes version in Mac OS X version 10.11.6 12.4.2.4 (El Capitan) on a MacBook Pro. When I go into iTunes and not select the option of internet radio stations under news / talk of work. For example, WMAL does not, and yet I can get the li

  • 5 - file already opened it occurs without open instance of Excel.

    Questions about my particular problem have been published several times and I've studied all.  But this problem is slightly different from what I found on the forum.  This issue I'm fighting for the past two weeks and I can't seem to find a solution

  • CD player that come out frequently

    CD come out automatically over and over again. When he gets out, I close to the top, but after awhile, it comes out again automatically. Especially when I start typing something (especially I observed by pressing the CR, tr, ed, yu, uy), it comes out

  • All-in-one Deskjet 2540 print not web pages

    I just installed this printer in wireless mode. It prints well applications like excel, word, acrobat, etc, but will not print pages from google, such as google maps and others.

  • Problem installing HP Officejet 4500 Windows 8.1

    I recently reinstalled my dad's computer. Earlier there was Windows 7, now it has updated to 8.1. The printer and scanner function worked correctly before, but now only the printer works. It was plugged during the installation of the OS and the print