Identifying Synthetic Fields via Reflection

Hi all,
I was wondering what the proper way is for identifying synthetic fields using the Reflection API. I am running into a problem involving the infamous "this$0" field, similar to the problem described in http://forum.java.sun.com/thread.jspa?forumID=4&threadID=484024 .
I need to traverse object graphs in a certain manner, and this$0 sends me into an endless loop unless I specifically exclude it. However, just going by the name "this$0" is not a safe way to indentify a synthetic field, as older compilers, or even the not-so-old Eclipse compiler, allow you to call any field "this$0". Therefore, a field named "this$0" may or may not be an actual synthetic field that links to the enclosing class instance.
Eclipse JDT bindings have a method 'isSynthetic()' but something like that does not exist in the Reflection API (at least I couldn't find it).
Does the Reflection API provide a safe way to check for the Synthetic attribute of a field?
Thanks in advance,
Mirko Raner
Parasoft Corp.

I tried that, in the hope the flag would also be present in pre-1.5 VMs, but unfortunately that's not the case. Up to JDK 1.4, synthetic fields were actually marked as an attribute, not as a flag. The actual flag that distinguishes synthetic fields was not introduced until JDK 1.5.
Anyway, thanks for the suggestions. It looks like my problem can only be solved with a hack (i.e., always assume "this$0" is synthetic) in pre-1.5 environments.

Similar Messages

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

  • Setting Fields value via reflection

    I'm starting from a c# code:
              internal void RefreshFromObject(object objFromUpdate)
                   if (this.GetType()==objFromUpdate.GetType())
                        PropertyInfo[] fieldsFrom = objFromUpdate.GetType().GetProperties();
                        PropertyInfo[] fieldsThis = this.GetType().GetProperties();
                        for(int idxProp=0; idxProp<fieldsFrom.Length;idxProp++)
                             if (fieldsThis[idxProp].CanWrite && fieldsFrom[idxProp].CanRead)
                                  fieldsThis[idxProp].SetValue(this, fieldsFrom[idxProp].GetValue(objFromUpdate,null),null);
                   else
                        throw new ObjectTypeNotValidException("Object type from which update current instance not valid. Use same type.");
    Now I have to translate it in Java:
    Class clazz = objFromUpdate.getClass();
    Class thisClazz = this.getClass();
    do {
         Field[] fieldsFrom = clazz.getDeclaredFields();
         Field[] fieldsThis = thisClazz.getDeclaredFields();
         try {
              fieldsThis[idxProp].set(thisClazz, fieldsFrom[idxProp].get(clazz));
         catch (IllegalAccessException iaccEx) {
              System.out.println("IllegalAccessException");
         catch (IllegalArgumentException iaccEx) {
              System.out.println("IllegalArgumentException");
    clazz = clazz.getSuperclass();
    thisClazz = thisClazz.getSuperclass();
    } while (clazz != null && clazz != Object.class);
    My problem is that I don't know if the field type is one of primitive, for which I should use the particular setters and getters.
    My questions are:
    1) is there in Java a more elegant way to set fields values via reflection?
    2) how can I know if a field i changable (equivalent to the method CanWrite of c#?
    Thanks a lot to each one that will answer me.
    Marco

    Hi georgemc,
    thanks for replying. I-m new with java forum, so I don't know if it is correct the code tags...
    Anyway... the problem is that the Field of reflected object could be both of Object types or primitive types. So I cannot use the general method "set" when changing Field's value.
    Maybe somebody else had the same problem...
    Seems in C# it is a very easy thing... not in java :(
    Marco
    Class clazz = objFromUpdate.getClass();
    Class thisClazz = this.getClass();
    do {
    Field[] fieldsFrom = clazz.getDeclaredFields();
    Field[] fieldsThis = thisClazz.getDeclaredFields();
    try {
    fieldsThis[idxProp].set(thisClazz, fieldsFrom[idxProp].get(clazz));
    catch (IllegalAccessException iaccEx) {
    System.out.println("IllegalAccessException");
    catch (IllegalArgumentException iaccEx) {
    System.out.println("IllegalArgumentException");
    clazz = clazz.getSuperclass();
    thisClazz = thisClazz.getSuperclass();
    } while (clazz != null && clazz != Object.class);

  • Loading a class via reflection without knowing the full qualified path ?

    Hi there
    I d like to load a class via reflection and call the constructor of the class object. My problem is that I dont know the full qulified name e.g. org.xyz.Classname bur only the Classname.
    I tried different things but none seem to work:
         1. Class c = Class.forName("Classname");  //does not suffice, full qualified name required
    2. ClassLoader classloader = java.lang.ClassLoader.getSystemClassLoader();
             try {
               Class cl = classloader.loadClass(stripFileType(Filename));//if i do not pass the full qualified name i get a ClassNotFoundException
    3. I tried to consruct a class object with my own classloader , calling:
              Class cl = super.defineClass(null, b, 0, b.length );     b is of type byte[]This almost works. I get a class Object without knowing the full qulified path. I can transform a filename into a raw array of bytes and I get the class out of it. But there is still a problem: If there are more than on classes defined in the same textfile I get an InvocationTargetException.
    It looks like this:
    package org.eml.adaptiveUI.demo;
    import com.borland.jbcl.layout.*;
    import java.awt.*;
    import org.eml.adaptiveUI.layout.*;
    import javax.swing.*;
    import java.awt.event.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2003</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class twoButtons extends JFrame {
      SPanel sPanel1 = new SPanel();
      JButton jButton1 = new JButton();
      GridBagLayout gridBagLayout1 = new GridBagLayout();
      GridBagLayout gridBagLayout2 = new GridBagLayout();
      public twoButtons() throws HeadlessException {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      public static void main(String args[]){
        twoButtons twob = new twoButtons();
        twob.pack();
        twob.show();
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(gridBagLayout1);
        jButton1.setText("button 1");
        jButton1.addActionListener(new TransformationDemo_jButton1_actionAdapter(this));
        this.getContentPane().add(sPanel1,  new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
                ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(57, 52, 94, 108), 35, 44));
        sPanel1.add(jButton1,  new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
                ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 41, 0, 0), 0, 0));
      void jButton1_actionPerformed(ActionEvent e) {
        System.out.println("button 1 source: " + e.getSource());
        System.out.println("d: " + e.getID());
       System.out.println("/n commmand: " + e.getActionCommand());
    class TransformationDemo_jButton1_actionAdapter implements java.awt.event.ActionListener {
      twoButtons adaptee;
      TransformationDemo_jButton1_actionAdapter(twoButtons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton1_actionPerformed(e);
    }As you can see there is the class TransformationDemo_jButton1_actionAdapter class defined in the same classfile. The problem is now that the twoButtons constructor calls the TransfomationDemo_jButton1_actionAdapter constructor and this leads to InvocationTargetException. I dont know if this is a java bug because it should be possible.
    Can you help me?

    hi thanks at first,
    the thing you mentioned could be a problem, but I dont think it is.
    If I have the full qualified name (which I havent) then everything goes normal. I only have to load the "twoButtons" class and not the other (actionadapter class), so I dont think this is the point. In this case the twoButtons constructor constructs an object of the actionadapter class and everything goes well. The bad thing is though that I do not have the full qulified name :(
    Invocation target exception tells me (in own words): Tried to acces the constructor of the actionadapter class (which is not public) out of class reflectionTest class .
    reflectionTest is the class where the reflection stuff happens and the twoButttons class is defineClass() ed.
    The problem is, only twoButtons class has the rights to call methods from the actionadapter class, the reflection class does not. BUT: I do not call the actionadapter methods from the reflection class. I call them only from the twoButtons class.
    I hope somebody understands my problem :)

  • Identifying form fields automatically when word doc is imported

    Hi
    I am trying to convert a word document template to a PDF template using Adobe Live Cycle. There are 7 tables in the Word document. I saved the doc as PDF using Word. When i imported the PDF into the Live Cycle Designer, the form fields ( table rows and cells) are not being identified. All are kind of static text.
    However, when i opened the same PDF in Acrobat Pro, i was able to identify the form fields ( using Form > edit fields option).
    Is there something similar available in Live Cycle Designer. Can the LCD identify form fields automatically.
    Appreciate your help.
    Thanks and regards
    Ram

    I don't believe this functionality is built into LiveCycle Designer. However, you can start your form in Acrobat (Acroform) then import the PDF into LiveCycle. Keep in mind this is a one way process.

  • How to Identify Delta Field in DS

    Hi Gurus,
      1. My understanding is if a field in datasource(DS) is
      set as Delta, whenever that field value changes in DS
      then the delta process will initialize. (please correct
      me if i am wrong) Do we need to replicate everytime
      the field value is changed so that the value is updated
      in the data target, if so is there a process to
      automate it...  
      2. Can someone tell me how to identify Delta Field in a
      DS for example in 0FI_AP_4. i tried to search for it in
      help.sap.com but all i could find is that 0FI_AP_4 is
      delta capable but couldn't find which field is set to
      delta...
    Thanks,
    SM

    Sri Mal,
       1. Yes, there should be one field enabled enabled for delta.
       2. no need to replicate every time when ever data changes. we need to replicate when DS changed. i mean not business data, if meta data changes we need to replicate the DS. let us assume you made one field for selection and one field as hide. then  you need to replicate this.
      3. OFI_AP_4 is standard DS. you can't enable delta for this one if SAP didn't provide that. we need to active data for this. in the SAP Documentation you can see whether it is delta capable or not.
    comming to 0FI_AP_4, IT IS DELTA CAPLABLE.
    Hope this helps.
    All the best.
    Regards,
    Nagesh Ganisetti.

  • How to provide the F4 help to a screen field via enhancement

    Hi,
    I have a transaction code IL01(Creating Functional Locations).
    In the second screen of FL creation,we can find 'Room' field under 'Location' tab.
    At present, it doesn't have F4 help.
    Could you please suggest me to provide the F4 help to this field via enhancement.
    I have values of that field in ine internal field.
    Thanks&Regards,
    VRLREDDY

    Hi,
    try something like this:
    INITIALIZATION.
      SELECT * INTO CORRESPONDING FIELDS OF TABLE so_setheader
               FROM    setheader
               WHERE   setclass = '0000'.
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR so_kost-low.
    * F4 uitvoeren
      CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
        EXPORTING
          retfield    = 'setname'
          dynprofield = 'so_kost'
          dynpprog    = sy-cprog
          dynpnr      = sy-dynnr
          value_org   = 'S'
        TABLES
          value_tab   = so_setheader.
    AT SELECTION-SCREEN ON so_kost.
      READ TABLE so_setheader INTO wa_so_setheader WITH KEY setname = so_kost-low.
      IF sy-subrc NE 0.
        so_kost = space.
        MESSAGE e333(s1) WITH 'Does not exist!'.
        STOP.
      ENDIF.
    Adibo.

  • Add new fields to default view when creating fields via REST in sharepoint 2013

    Hello,
    When I add new fields via REST in a list, they don't appear in the default view for that list.
    Here is my code in case you need it:
    public function creeChamp(nomListe:String, champ:String, type:int, requis:Boolean):void
    postURL.data = JSON.stringify({ '__metadata': { 'type': 'SP.Field' }, 'Title': champ, 'FieldTypeKind': type,'Required': requis, 'EnforceUniqueValues': false,'StaticName': champ});
    thanks

    You need to add the field to the view as well.
    Here is the API.
    Our code looks pretty different because I'm working in AngularJS, but here's a snippet from a working example:
    $http.post(siteUrl + "/_api/web/lists/GetByTitle('" + listName +
    "')/Views/GetByTitle('All%20Items')/ViewFields/addViewField('" + columnName + "')",
    // POST data is empty for this request
    }, getPostConfig())
    .then(function (response) {
    deferred.resolve("Added column to view");
    .catch(function (response) {
    deferred.reject('Error ' + response.status + ': ' + response.data.error.message.value)
    Bottom line is you just POST to this URL however you normally do - except no data:
    "/_api/web/lists/GetByTitle('" + listName + "')/Views/GetByTitle('All%20Items')/ViewFields/addViewField('" + columnName + "')",
    Hope this helps!
    - Bob

  • Data missing in Crosstab report with calculated field via case when

    I use the Oracle 10g discoverer. When I create a crosstab report with a calculate field via function case when and put it as datapoint, some of the data is not showing. I tried to not use the case when function for the calculate field, then all the data show.
    I really do not the reason. Could anybody help me out with many thanks?

    Let me explain more.
    I have the original data below.
    Work order, Team, Hours_worked, date
    800001, S1, 5, 2012/01/01
    800001, S1, 15, 2012/01/10
    800001, S2, 4, 2012/01/04
    800002, S1, 3, 2012/01/15
    There are multipul records for the same work order, team on the same day or different.
    Finally I want to set the start date and end date as the parameter to create a crosstab report format like
    start date>=2012/01/01 and close date<=2012/01/05
    Team
    Total hours total hours within the range
    Work order S1 S2 ... S1 S2 ...
    800001 20 4 5 4
    800002 3 0 0 0
    in order to do it, I create two parameters independently start date and close date. Then I create a calculate field hours_worked_withinrange via
    Case when date>=:start date and date<=:end date then Hours_worked else 0 end
    This calculated field is correct in the tabular format report in discoverer desktop. But when I duplicate the list as crosstab. Some data is missing in crosstab data point.
    I checked once I change the calculate field defination not use case when. (For example, C1=hours_worked*2). Then everything runs correct.

  • New field not reflecting in Table maintenance generator

    Hi Experts,
    I have added a new field in a ztable.I regenerated the table maintenance generator,so that the  new field is reflecting in devlopment system , also a TR got created.When i moved this TR to pre-production system new fields are reflecting in the structure of table but not in table maintenance generator.
    Please suggest solutions.
    Regards,
    Niranjan

    Hi Experts ,
    I have gone through the steps which is mentioned.But still issue is pending,the changes in TR are not reflecting in pre prod.
    Error after moving the TR with "Definition of a Maintenance and Transport Object".
    The current ABAP program "SAPLSVIM" had to be terminated because it has
    come across a statement that unfortunately cannot be executed.
    The following syntax error occurred in program "SAPLZFGL " in include "LZFGL$03
      " in
    line 13:
    "Field "ZCHAR_FIXED_WIDTH" is unknown. It is neither in one of the spec"
    "ified tables nor defined by a "DATA" statement. ."

  • Restricting HR Tables fields via auth object?

    Happy Holiday's everyone!
    We have a custom tcode for Pricing Admin report which currenltly only has S_Tcode for an auth obj.  It was combined in a role that we removed the HR authorization from and apparently these were interdependent but undocumented.  Now the pricing transacation no longer functions. 
    Instead of just adding back the missing HR authorizations back into the custom Tcode I'm being asked if  we can restrict PA00002 (the table being called in the program) to first name, last name and personnel number fields.  Is there an authorization object that will let me restrict in this manner or do I need send this back to the developers to write in the code? 
    Or can I restict to these fields via authorization groups (something we are looking into implementing more next year).
    Thanks
    Kris Wise

    That is a bad omen for the next year...
    Try to change the code this year still to deliver only the fields you want from the infotype or go for an "existence check" which no authorization requirements as that is what you seem to be wanting.
    Being custom code, you should post the problematic part to discuss a solution.
    Cheers,
    Julius

  • 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

  • Client would like the monetary fields to reflect . and not , in the fields.

    Client would like the monetary fields to reflect . and not , in the fields. There are commas and he wants decimals.
    can any one help me out, this is a tkt  can any one suggest me how do we take it further.

    Hi Jai Ram,
    Ask the user to go to SU3 tcode. Then go to defaults tab. There is a field called Decimal Notation. There are three formats as below
    1.234.456,789
    1,234,456.789
    1 234 456,789
    Select accordingly. Then quit SAP and relogin. The changes will be applied.
    Kind Regards
    sandeep

  • Update trigger: identify which field changed

    Is there any way to identify which field was changed when an update trigger fires? I need to be able to update another field if any field excluding 1 was changed.
    Something like
    for each field in :new
    if field.name != "dateref" then
    if field.modified then
    altered=true
    exit for
    endif
    endif
    next
    if altered then :new.updatetype="A"

    This will do it
    CREATE OR REPLACE my_trigger BEFORE UPDATE
    OF col2, col3, col4 ON my_table FOR EACH ROW
    BEGIN
      :new.updatetype='A';
    END;
    /If your table has a lot of columns this will be a bit of a drag to type all those column names. Unfortunately, as far as I know, there is no OF ALL COLUMNS EXECPT col1 ON
    syntax.
    Cheers, APC

  • How to identify mandatory fields while using an idoc

    Hi
    I am new to Idocs. I want to find out the mandatory fields in the segments that are used in an Idoc.
    Please help.
    Regards,
    Lohitha

    Hi Lohitha,
    I dont think there is a straight forward/documented way of knowing a mandatory field within a segment, however you can use WE30 or WE60 to identify the mandatory segments in an IDOC.
    I guess you will have to use common knowledge of the requirement to know/identify a field that might be mandatory. For Ex: when you are creating an ITEM on a SO, Material  is mandatory etc
    Regards,
    Chen

Maybe you are looking for

  • How to get the localization in adf

    Hi Experts, Can you please tell me how to achieve the localization in adf application.?? I want it to support for based on locale.. Can you please tell me the procedure.... I am using jdev 11. Here I need localization in VO layer.not using resource b

  • Problems with iPhone messaging - received messages showing as sent messages and messages sent to one family member gets received by other family members.

    AT&T family plan - 4 iPhones in use by family members (4s, 4g, and two 3g's).  Weird things happen when we text message: 1.   Sometimes, received messages look like they are sent messages - and no alert is sounded.   The conversation looks like you a

  • FRM-40737 Error, While using COMMIT_FORM

    Hi, Please guide for the following: In a form, I have two data blocks,namely master and detail. In PRE-INSERT trigger of master block, I am using GO_BLOCK('detail'). The form has a SAVE_BTN also, in save_btn i am using COMMIT_FORM. When user clicks s

  • How to transfer data between different nodes of the same context.

    Hi experts,    I am working on an application in ABAP webdynpro in which i want to copy data from one node to another node in the same context of a view and both the nodes are mapped with different nodes of context of component controller. How to cod

  • Manual for Element 11

    I just paid $100.00 for the Element 11 software. Why is there NOT a manual included?? Sure it comes with the "get stated pamplet", but I need something to read as I edit photos. To download and copy from PC will eat up my ink>> ( over 400 pages)