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);

Similar Messages

  • How to set variables values via VBA.

    Anybody please help.
    How to set variables values via VBA in workbook. SAP Netweaver 2004s.

    Pass variable values with VBA and BI 7.0 funtions to Query
    At first a remark u2013 Iu2019ve read a lot of threads saying that passing values to a query can be done by using VBA code only. Iu2019ve tested it but Iu2019m not sufficient with the new BEX 7.0 API and therefore I use a mixture of BEX 7.0 funtionality and VBA. I create a BEX 7.0 design item button passing the values to a query u2013 I hide this button somewhere on the sheet or on a hidden sheet and I then raise the event to click the button from VBA code. Works fine and the maintenance is easier if something changes in the API in the future again.
    How to start:
    Switch to design mode in BEX Analyzer:
    Implement a BEX 7.0 design item u201Cbuttonu201D
    Click on the button to implement the properties
    Make the input for the commands
    data_provider = dataprovider_1
    cmd = process_variables
    subcmd = var_submit
    No comes the part with the variables u2013 Letu2019s assume a query has 4 variables but you only want to change 1 with the button u2013 an organizational unit for instance.
    Make a range somewhere in the excel with the following structure:
    Name    Index   Value
    VAR_NAME_1      1       Variablename
    VAR_VALUE_EXT_1 1       variablevalue
    Value should contain the name of your variable of course and u201Cvalueu201D the value of your variable
    Set a name for this range with EXCEL functionality but without the header:
    Back to the properties of the button: Insert the name of the range with the variables in the field Command Range:
    If you have more variables to process you can of course enhance your Filterrange!
    In the left upper Corner you have a name for your button:
    Now you can raise the button-click in vba like this:
    Application.Run "'" & ThisWorkbook.Name & "'!Sheet2.BUTTON_35_Click"
    regards, Lars

  • How to set field value in workflow SPD2013?

    Hi All,
    how to set field value in workflow SPD2013? Actually using Infopath, i need to update a field value through workflow.(Little differnt from SPD2010). How to do this?

    As Amit says, some elaboration here would be good.  You can use InfoPath as a form for either a list or a library and then set it to trigger a workflow upon item creation.  The workflow will consist a number of actions, one of which is the Update
    Field Item.
    More information on the available steps can be seen here.
    http://msdn.microsoft.com/en-us/library/office/jj164026.aspx
    Steven Andrews
    SharePoint Business Analyst: LiveNation Entertainment
    Blog: baron72.wordpress.com
    Twitter: Follow @backpackerd00d
    My Wiki Articles:
    CodePlex Corner Series
    Please remember to mark your question as "answered" if this solves (or helps) your problem.

  • Set field value problem

    Hi All,
    I want to set a field value of a class. I do this in the way of modifying codes in getText() method in XXXItemProvider.java as the red frame in the following picture.
    It generates the following problem
    But, if I remove the codes, "(NFRSoftgoal)object.setLabel......", it becomes normal.
    Can anyone help me solve the problem?
    Thanks & Regards,

    Comments below.
    On 17/07/2015 7:19 PM, Shin-Yi Lin wrote:
    > Ed Merks wrote on Fri, 17 July 2015 12:28
    >> Comments below.
    >>
    >> On 17/07/2015 4:40 AM, Shin-Yi Lin wrote:
    >>> (1) My model structure (I want to change label attribute.):
    >> So the label feature is on a class that's the root of a several other
    >> classes...
    >> ----> Yes.
    >>>
    >>> (2.1) Before (Child and parent clouds are undecided. Cloud represents NFRSoftgoal class.):
    >> This undecided thing is the default state...
    >> -----> That's right.
    >>>
    >>> (2.2) After (After child cloud changes to satisfy through command, parent cloud changes to satisfy automatically.)
    >> Is this via a command that directly modifies the label feature of the
    >> "child"? If so, that's the place to modify the state of the parents,
    >> e.g., using a compound command that modifies the child as normal, and
    >> walks up the parents to modify the parent label also using commands.
    >> What, if anything, prevents the "parent" label from being directly
    >> changed back to undecided (which is perhaps an inconsistent state for
    >> the model)?
    >> -----> I change the label feature of "child" through the red frame in the following pictures (This is under run-time application and Sirius environment.):
    >>
    >>
    >> -----> But I don't want to change the label feature of "parent" through the same way, because it should be automatically changed, not manually.
    I'm asking what's preventing that from happening? I suppose it doesn't
    matter if you've done something so that only a leaf/child can be
    directly modified.
    >> That's why I modified the code of getText( Object object) function in NFRSoftgoalItemProvide.java under bpmn.edit.
    That's not a good idea.
    >>
    >>
    >>
    >> -----> What do you mean "via a command" ? I don't know how to change via a command. Could you explain or give any reference for it?
    On the child, the set command is created by
    org.eclipse.emf.edit.provider.ItemProviderAdapter.createSetCommand(EditingDomain,
    EObject, EStructuralFeature, Object) so you can specialize this method
    of the child's item provider so that it modifies not only the child's
    label feature, but modifies also the parents. All that could be done
    with a CompoundCommand that composes all the SetCommands.
    >>
    >> Thanks & Regards,
    >>

  • Deleting date field value via import

    I need to clear the value in a date field for a few thousand records. I tried doing this via import by setting the value to a space " " but it didn't work.
    Any ideas on how this can be achieved through import or otherwise would be great.
    Thanks.

    Hi Nakul,
    Try any of the following, it will hopefully work in your case:
    1) Import using excel with blank date field (no data in date field). This will erase the already existing value in the date field [provided there is no workflow that restricts such deletion of date data.]
    2) Create a temp workflow on condition "before modified record saved" and update the date field value with blank (no values in fx), do the import, this workflow will delete the existing data.
    Cheers!
    Vix

  • How to Set Field value using javascript?

    I have a Field in First Page called 'SO'. I want to populate this field from the field value of SD_ITEMS.DATA.VBELN first row in the each page. Please help me with javascript to set this value.
    Thank you.
    Ranji

    I have a Field in First Page called 'SO'. I want to populate this field from the field value of SD_ITEMS.DATA.VBELN first row in the each page. Please help me with javascript to set this value.
    Thank you.
    Ranji

  • HELP - i can't set field value in a form

    Hi,
    I created a form based on a stored procedure.
    I try to set a field value on this form( the name of the item in the wizard is 'P_GG') from the advanced PL/SQL SECTION in the wizard, and, for exact, in "... before displaying the page..." i wrote:
    p_session.set_value(
    p_block_name => 'DEFAULT',
    p_attribute_name => 'A_P_GG',
    p_value => '20');
    But when I run the form the field is blank
    Thank for everyone reply and help me.
    Simone Mancino

    Dmitry,
    thank u for your reply.
    I tried your solution, but there is another problem. I specified a default value for the form, using the syntax "#myfunction()".
    The first time I run the form, i get the correct value. But whenever i run the form again in the same session, I always get the FIRST value: it looks like the function is not evaluated again. For example, suppose the function is
    return to_char(SYSDATE, 'SS')
    (just to have a random dynamic value);
    you always get the value of the first run, even if you refresh the page.
    Regards
    Simone

  • Setting field value from antother field

    I am having problems setting the value of a field depending on the entry of a previous drop down field.
    I am creating some wizard pages. On one page i wish a drop down list to populate another field. The drop downlist is unbound. (I have tried doing this with bound field aswell). To do this I have the Depends on Item of the target field to depend on the dropdown list field, so that the appropriate values are updated. (i have tried with the target field being bound and unbound aswell not that it should matter).
    I have then updated the VO (view object) adding transient fields when the fields are unbound. Then i updated the view row class. The setter of the drop down field was used to set the value of the target field. (Using the setter of target field). I added system.out.println and the fields are called and set accordingly. ie getters and setters are correct.
    However when i run the screens the target field value is not set with the value within the getter of target field.
    Could you advice if this is a bug or whether i should be coding this in a different manner. (if it is a bug and you tell me when it is likely to be fixed and any alternative work arounds).
    Cheers
    Alan

    Alan,
    Not really a bug, but "missing functionality". The problem is that ADF Faces will only refresh a UI Component value from the underlying model binding value when you submit the request with immediate="false", OR when you explicitly call resetValue() on the component.
    We have added a new boolean item-level property "Clear/Refresh Item When Depends-On-Item Changes" in the latest build.That property will do the trick for you: it will clear the value and call resetValue on the UI Components of the dependent items, BEFORE the depends-on-item model value is updated. So, in your case, the setter method of your depends-on-item attribute will update your dependent item after JHS cleared the item, and you will see the new value right away because UIComponent.resetValue() was called as well.
    Steven Davelaar,
    JHeadstart Team.

  • Set field value in Discussion Board Reply

    Hi all,
    I need to set the value of a field in all discussion board replies within a discussion. In my example, I need to pass a value from the discussion board item to all of the replies (ex. when a reply is made, I want a field named "Project Number" to be populated
    by the Project Number set when a Discussion is created). I need this so I can email out varying users related to the Project Number.
    Thanks,
    Kelly
    Personal Blog: http://thebitsthatbyte.com

    Hi
    SPQuery query = new SPQuery();
    query.Folder = discussItem.Folder;
    SPListItemCollection replyCollection = ctxList.GetItems(query);
    foreach (SPListItem itemReply in itemCollection)
    itemReply["FIELD_TO_UPDATE"] = VALUE;
    itemReply.SystemUpdate(false);
    discussionItem: is a discussion item
    ctxList: is a current discussion list
    If there are many reply items need to be update, please build an update string and use BatchUpdateProcess command to perform update with best performance.
    Hope this help.
    Visit my blog: My Blog | Visit my forum:
    SharePoint Community for Vietnamese |
    Bamboo Solution Corporation

  • Set Field value

    I have placed several fields in my form. I want to set the value of those fields through code. How do i do this. Under what trigger do I have to write this code? It would be helpful if you could be a bit specific as I'm really new to Reports.

    Something like this ? (in general)
    - In your data model create your query from CASES table.
    - Use layout wizard to do the layout (for example)
    - for example you need an additional column that is something like calculation that can't be done using sql query, then create a formula column in your data model.
    - click properties for that formula column,change the data type and width accordingly.
    - click pl/sql formula, enter your calculation there.
    - put your new fields in the layout model.
    You can tell me which one you need me to explain in details.

  • Set field value whiel calling MM12

    How Can I set the value of Schedule data to some value.
    I am calling MM12 with material Number and Date.
    I can set the material Number because it has parameter ID. How can I set the value of schedule date ?. it doesn't have parameter ID. Schedule date is mandatory field.
    I need to call the MM12 Skip first screen.

    Do you think that you can use a partial BDC?
    report zrich_0003
           no standard page heading line-size 255.
    data: bdcdata type table of bdcdata with header line.
    data: bdcdate(10) type c.
    parameters: p_matnr type mara-matnr,
                p_datum type sy-datum.
    start-of-selection.
      call function 'CONVERT_DATE_TO_EXTERNAL'
           exporting
                date_internal = p_datum
           importing
                date_external = bdcdate.
      perform bdc_dynpro      using 'SAPLMGMM' '0060'.
      perform bdc_field       using 'BDC_CURSOR'
                                    'RMMG1-AEDAT'.
      perform bdc_field       using 'BDC_OKCODE'
                                    '/00'.
      perform bdc_field       using 'RMMG1-MATNR'
                              p_matnr.
      perform bdc_field       using 'RMMG1-AEDAT'
                              bdcdate.
      call transaction 'MM12' using bdcdata mode 'E'.
    *        Start new screen                                              *
    form bdc_dynpro using program dynpro.
      clear bdcdata.
      bdcdata-program  = program.
      bdcdata-dynpro   = dynpro.
      bdcdata-dynbegin = 'X'.
      append bdcdata.
    endform.
    *        Insert field                                                  *
    form bdc_field using fnam fval.
      clear bdcdata.
      bdcdata-fnam = fnam.
      bdcdata-fval = fval.
      append bdcdata.
    endform.
    Regards,
    Rich Heilman

  • 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 primary key field value in jdoPrestore() not flushed to database ?BUG?

    Hello,
    When I set value of primary key field of a new instance in jdoPrestore() new
    value does not get flushed to database - old (default) value get stored
    instead. All other fields assigned in jdoPrestore() get successfully
    flushed except primary key one.
    Alex

    Abe,
    You fixed only part of the problem. Right now if I assign value to a PK
    field in jdoPreStore() it does get flushed but there is another issue - all
    other instances which referenced the one I assigned PK to will not get this
    PK value. Example A references B, in B.jdoPreStore() I generate id for B -
    b.id = 100. When A gets flushed it would not get 100 in its b_id field.
    Specs says:
    This method is called ***before the values are stored from the instance to
    the StateManager***.
    Data store fields that might have been affected by modified non-persistent
    fields should
    be updated in this method. This method is modified by the enhancer so that
    changes to
    persistent fields will be reflected in the data store.
    The context in which this call is made allows access to the
    PersistenceManager and
    other persistent JDO instances.
    I read it as callbacks should be invoked on ALL instances before they get
    stored to StateManager. Does Kodo invoke callbacks for all istances first
    and then store them to instance manager? Based on the problem I am having it
    does not look like it
    Alex
    "Abe White" <[email protected]> wrote in message
    news:[email protected]..
    I just confirmed this as a bug and fixed it. We should be able to post
    the new jars for you soon. Hang in there.

  • How to set a particual field value as sysdate if it is null

    Hi,
    I have a requirement in custom OAF page.
    In the results table, if DATE field value is NULL, then we need to set it as SYSDATE by default.
    For this I'm using the following code. Could anyone suggest me whether I'm doing correct or not?
    PFR CO Code:
    if(xxMDateBean == null)
    OAMessageDateFieldBean xxMDate = (OAMessageDateFieldBean)webBean.findIndexedChildRecursive("xxMDate");
    oracle.jbo.domain.Date date1 = am.getOADBTransaction().getCurrentUserDate();
    java.text.SimpleDateFormat displayDateFormat = new java.text.SimpleDateFormat ("dd-MM-yyyy");
    String OracleDateForm = displayDateFormat.format(date1.dateValue());
    xxMDate.setValue(pageContext,OracleDateForm);
    I am getting the following error:
    Error(81,8): variable xxMDate not found in class (CONTROLLER)
    Edited by: Sruthi on Jan 20, 2011 5:09 PM

    Sruthi,
    Sorry I missed the point that the field is in the table region.
    Now my understanding is, you have a display table, which has a column of Type Date,
    If the query returns null for that value, you want to display the sysdate is it correct?
    If yes, please change ur logic little bit,
    I am sure you will be calling an AM Method to execute the VO,
    In your AM, after the execution, traverse throw the Rows,
    And check for the dateColumn value and then set Sysdate, which will reflect here.
    Sample code:
    locatorVO.executeQuery();
    XXPOLocatorVORowImpl locatorVORow = (XXPOLocatorVORowImpl)locatorVO.first();
    while (locatorVORow!=null)
    //get the dateValue and check it is null
    if(date is null)
    Date currentDate = this.getOADBTransaction().getCurrentDBDate();
    locatorVORow.setOrderedDate(currentDate);
    locatorVORow = (XXPOLocatorVORowImpl)locatorVO.next();
    Thanks,
    With regards,
    Kali.
    OSSI.

  • Issues updating/setting multi value lookup columns via powershell

    Hi All,
         I have an issue updating multi values in a lookup field via powershell
    I can update a single value  lookup field as below but can't get to update if its multi value.
    As stated below when I hardcode it. It works.
    No idea what 'm missing. Any help will be appreciated.
    #Hardcoded works below as you can see i'm setting 3 values
    $array = @($realval.Split(';'))
    for ($i = 0; $i -lt $array.Count - 1; $i += 2)
    $word = $array[$i].Trim('#')
    $number = $array[$i+1].Trim('#')
    "$number $word"
    $lookupvalue1 = GetLookUpValues -val $number
    [Microsoft.SharePoint.SPFieldLookupValueCollection] $itemValues = New-Object Microsoft.SharePoint.SPFieldLookupValueCollection
    [Microsoft.SharePoint.SPFieldLookupValue] $lookupvalue = New-Object Microsoft.SharePoint.SPFieldLookupValue
    [Microsoft.SharePoint.SPFieldLookupValue] $lookupvalue2 = New-Object Microsoft.SharePoint.SPFieldLookupValue
    [Microsoft.SharePoint.SPFieldLookupValue] $lookupvalue3 = New-Object Microsoft.SharePoint.SPFieldLookupValue
    $lookupvalue.LookupId = 1
    $lookupvalue2.LookupId = 2
    $lookupvalue3.LookupId = 6
    $itemValues.Add($lookupvalue)
    $itemValues.Add($lookupvalue2)
    $itemValues.Add($lookupvalue3)
    #$itemValues.Add($lookupvalue)
    $CMRSItems["Event Type"] = $itemValues;
    Write-Host "items:" $itemValues
    $CMRSItems.Update()
    # This works when its updating only one value but when it needs to update multivalue it only updates the last one
    #so for example with the lookupvalue above only 6 gets updated below
    $array = @($realval.Split(';'))
    for ($i = 0; $i -lt $array.Count - 1; $i += 2)
    $word = $array[$i].Trim('#')
    $number = $array[$i+1].Trim('#')
    #$number
    "$number $word"
    #send param to GetLoolValues func to return records as SPFieldLookupValue
    $lookupvalue1 = GetLookUpValues -val $number
    #I can view the lookupvalue returned successfully
    #Write-Host $lookupvalue1
    [Microsoft.SharePoint.SPFieldLookupValueCollection] $itemValues = New-Object Microsoft.SharePoint.SPFieldLookupValueCollection
    #This LookupId returns 3 values like on the hardcoded one above like so :1,2,6
    $lookupvalue.LookupId = $number
    $itemValues.Add($lookupvalue)
    $CMRSItems["Event Type"] = $itemValues;
    #I can view the items returned successfully
    Write-Host "items:" $itemValues
    $CMRSItems.Update()

    The problem I can see with your code is that the below line of code, you are instantiating inside the for loop. This should have been outside the for loop as by keeping it inside the loop you are overriding the value.
    [Microsoft.SharePoint.SPFieldLookupValueCollection] $itemValues = New-Object Microsoft.SharePoint.SPFieldLookupValueCollection
    Please have a look at the below solution and modify your code as per your requirement. What I am trying to achieve in the below code is that I have a listA in which one of the field is being used as a multi-lookup in my listB.
    $lookupCollection = $something.split(";")
    $LookupMasterList=$web.Lists["ListA"]
    [Microsoft.SharePoint.SPFieldLookupValueCollection] $lookupValueCollection = New-Object Microsoft.SharePoint.SPFieldLookupValueCollection
    #Get the Lookup Item from Parent List
    foreach($item in $lookupCollection){
    IF([string]::IsNullOrEmpty($item.trim())) {
    continue;
    $LookupItem = $LookupMasterList.Items | Where-Object { $_.Item("FieldInternalName") -eq $item.trim()}
    if($LookupItem -ne $null)
    $myLookup = New-Object Microsoft.Sharepoint.SPFieldLookupValue($LookupItem.ID,$item.trim())
    $lookupValueCollection.Add($myLookup);
    #Set the Lookup field value
    if([string]::IsNullOrEmpty($lookupValueCollection)){
    continue;
    else{
    $newItem["Lookupfieldinternalname"] = $lookupValueCollection
    The above logic has no hard coding and it fetches the lookup information directly from the master list and generates a collection based on that. You can modify the above code as per your requirement.
    Geetanjali Arora | My blogs |

Maybe you are looking for

  • Opmn service does not start when try to start Oracle BI Services

    Hi , I was able to install OBIEE 11g on my laptop and it worked fine for two days. Today when I try to login to rpd and type my user name and password I get the error that my user name and password is not correct. I tried to restart the machine and n

  • Fade in – images

    Hi there – I need help with this problem. I'm not a Flash person but | have collated various bits of tutorials from different forums and have 90% what I need – but it's just not there. I don't want anything fancy – just 780x250 banner that rotates ge

  • How can I print two sided? Linux, Epson 845

    The "print two sided" box is greyed out. I am running Linux on an Epson Workforce 845. I have no problem on a Windows 7 machine.

  • Why hibernate..why not ADF BCs

    Hello  ADF  experts,  I have been noticing that many big companies are using hibernate for business components  instead of ADF business components.  And  I got the answer for reason is  security issue.   If that is the case is it a big waste that we

  • Module with cpvc slides not working after uploading to LMS

    Everything works fine when previewing, but when it's uploaded to our LMS, it fails to load the video but continues to show the objects (shapes, text boxes) in that video slide.