Accessing Private variable using reflection

Is someone have code snippet for accessing private varaible using reflection
Here is my code snipper
import java.lang.reflect.Field;
public class test1234 {
private String t;
public test1234() {
public String show() {
return t;
import java.lang.reflect.Field;
public class Test123 {
public Test123() {
public static void main(String[] args) {
test1234 test12341 = new test1234();
try {
Class cls = test12341.getClass();
Field fld = cls.getField("t");
fld.set(test12341, "12");
catch (Exception e) {
System.out.println(e.getLocalizedMessage());
I am getting exception when i try to access.
java.lang.NoSuchFieldException
     at java.lang.Class.getField0(Native Method)
     at java.lang.Class.getField(Class.java:826)
     at Test123.main(Test123.java:24)
Thanks in advance

Thanks for your response. After setting accessible to true i can able to set into private variable.
Thanks a lot.

Similar Messages

  • Accessing ICS variable using EL

    Can we access ics variable using EL. Hope this query is already posted. but I tried the solution. it is not working
    I have set an  ics variable in a CSElement and I tried to access that in the next line using EL. but I am not getting the values
    e.g
    <%
    ics.SetVar("testvar","testvalue")
    %>
    fetching value using cs : {cs.testvar}
    fetching value using ics : {ics.testvar}
    No results for both the line. Is it not possible to access ics object using EL?

    Hello
    Could you try something like:
    e.g
    <%
    ics.SetVar("testvar","testvalue")
    %>
    fetching value using cs : ${cs.testvar}
    Hope it helps.
    Gerardo

  • How to access Websphere variables using java

    Hi
    I want to access Websphere variables using java.
    Any help is appreciated!!
    Thanks
    P

    WebSphere Application Server has a bunch environmental variables such as log locations. These are held at the "server", "node", and "cell" level.
    To access them, you have to get the right context. Something like this, I believe...
    InitialContext initialContext = new InitialContext();
    initialContext.lookup("foo:bar/baz/blah"); //correct context hereGo to the IBM website for WAS and do a search on namespace bindings. That should give you some more information.
    Good luck.

  • Get Name of Variable using Reflection

    Is there a way to get the variable name?  I assume I'd have to use Reflection.  Here's an example of what I mean.
    Dim tileCount As Integer
    ' get tileCount variable name here
    Debug.Print("tileCount")
    Ryan

    I need to validate a variable.  If the variable isn't valid I want to throw an ArgumentOutOfRangeException.
    Variable names are internal to your program.  They don't actually exist as part of your executable code, but it is possible with reflection to look back into the source code and find certain information.   But it is not possible
    to identify a variable by its value. However, you should not be using variable names to identify your objects.
    If you create a class for your values then you can build a IsValid test for the value field of the class, and return information about the class instance.  For example:
    Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim thisTile As New Tile With {.Height = 7, .Name = "Fred"}
    If Not thisTile.IsValidHeight Then
    Throw New ArgumentOutOfRangeException("Instance", thisTile.Name, String.Format("{0} is not a valid tile height.", thisTile.Name))
    End If
    End Sub
    End Class
    Public Class Tile
    Public Name As String
    Public Height As Integer
    Public Function IsValidHeight() As Boolean
    Dim myArray() As Integer = {3, 4, 6, 7}
    If Not myArray.Contains(Me.Height) Then
    Return True
    Else
    Return False
    End If
    End Function
    End Class
    Great idea! :)
    Still lost in code, just at a little higher level.

  • How to discover private field using reflect?

    Hi, all:
    i learned discover fields of a class by using reflect
    getClass().getFields()
    but it only works for public fields. how to discover all
    fields of a class?
    thank you in advance.
    kevin.

    I would not think that you would be able to use reflection to obtain private fields as even if you could get them, you cannot access them outside of the intansiated object of that type.
    what do you want them for?

  • Accessing private variables

    I'm a little confused. I know that using private instance variables is good practice, and that the appropriate way to access those variables is with accesser methods (getXXX(), etc.). Since the variables are private, you can't access them by just referring to "testClass.variable", right?
    Well, I was reading up on the Comparable interface today, and found a code example where a class implemented a compareTo() method like this:
    public int compareTo(Object o) {
       if (privateVariable < (TestClass) o.privateVariable) {
          return -1;
       } else {
          return 1;
    }But privateVariable is declared as a private variable. So why is it that you can refer to o.privateVariable in the compareTo() method? Is it just because o is cast as a TestClass object, and the compareTo() method is inside of the TestClass class? Even if that's the case, it still seems weird to me; if privateVariable is declared private, I'd think that any reference to a TestClass.privateVariable variable would throw an exception, even if the reference is within the TestClass. This just seems different to me than referring to the privateVariable variable within TestClass, because that obviously refers to the member of the current instance, not a different instance.
    Anyway, any explanation would be appreciated.
    Rich

    Yes, 'private' means 'private to this class', not 'private to this object'.
    In this way, it behaves somewhat like a 'friend' variable. The basic idea of making variables private is to hide the implementation behind a class, which still holds even with the compareTo method (you can't use it to figure out that there's a variable called 'privateVariable', when using it from outside your class.)

  • Accessing database Variables using JDBC

    Hi,
    I have a question for some of you Java specialists out there.
    I want to execute a select statment in my database (SQL Server 2000) and store the output in a variable. - The reason I am not directly executing the SQL statement from my JDBC connection is that I need to execute a number of SQL statements and then finally would like to store my result set in a variable in the database - NOW, my question is , how do I (If I can) access a database variable using either servlets or JSP. Any help is welcome.
    A quick response would be much appreciated.
    thanks

    We are probably talking about different things.
    ASP, at least when I used consisted of the following:
    -html
    -server side script (vbscript, javascript, perlscript)
    -client side script (usually javascript but it could be vbscript and perlscript)
    In the above you have three possible kinds of variables java, perl, vb. In each of those languages you can use SQL text to manipalate data in the database. However the text itself never ran in the ASP server nor was there such a thing a SQLscript, so there was nothing that was a SQL variable.
    However, if I write a stored procedure in Oracle, it can definitely have variables. And likewise a oracle package can have variables. But there is no way to directly use those variables in ASP. The value of the variable would have to be returned to the ASP script language and a variable in tha language could contain that value.
    Perhaps I just don't understand ASP or it has evolved in the last 3 years. If so then ignore everthing I have said.

  • Accessing TestStand Variables using Applicatio​n Manager

    I am working with an Operator Interface written in LabWindows/CVI 7.1.  I need this program to be able to access station globals and local variables in TestStand 3.1.  This Operator Interface was originally written for TestStand 2 and uses the older functions like TS_NewEngine, TS_EngineSetProperty, TS_PropertyGetValString, etc.  This has caused some problems when I try to use these functions with TestStand 3.1.  I can run the code fine in the debugger, but my executable just quits as soon as it encounters one of these older testStand functions (I can't tell which one).  I have been trying to incorportate the Application Manager, Sequence File View Manager, and Execution View Manager into the existing code without altering the GUI's appearence (keeping with the standard LabWindows text boxes and not using ActiveX controls).  I cannot figure out how to access variables in testStand using the Managers.  Here is the code I am using so far:
    //Define Panel Handles and ActiveX Control Handles
    typedef struct
     //panel handles
     int              m_pnMain;
     int              m_pnExecute;
     // ActiveX control handles:
     CAObjHandle applicationMgr;     // invisible control, manages Startup/Shutdown, and other application functions
     CAObjHandle sequenceFileViewMgr;   // invisible control, manages a SequenceView control that displays loaded sequence files
     CAObjHandle executionViewMgr;    // invisible control, manages a SequenceView control that displays executing sequences
     CAObjHandle m_oEngine;
     } ApplicationWindow;
    static ApplicationWindow gMainWindow; // this application only has one window
       // load the panels for the main window from the .UIR file
       errChk( gMainWindow.m_pnMain = LoadPanelEx (0, "Symtx Operator Console.uir", PN_MAIN, __CVIUserHInst));
       errChk( gMainWindow.m_pnExecute = LoadPanelEx (gMainWindow.m_pnMain, "Symtx Operator Console.uir", PN_EXECUTE, __CVIUserHInst));
       // prepare to use the TestStand ActiveX controls
       errChk( GetActiveXControlHandles());
       tsErrChk( TSUI_ApplicationMgrGetApplicationWillExitOnStart(g​MainWindow.applicationMgr, &errorInfo, &appWillExitOnStart));
       if (!appWillExitOnStart)
        // show a splash screen while starting up
        errChk( splashPanel = LoadPanelEx(0, "Symtx Operator Console.uir", SPLASH, __CVIUserHInst));
           errChk( InstallPopup(splashPanel));
       // make TS engine conveniently accessible
       tsErrChk( TSUI_ApplicationMgrGetEngine(gMainWindow.applicati​onMgr, &errorInfo, &gMainWindow.m_oEngine)); 
    The code shown above works fine.  I tried to add the following lines to access the station globals:
       // Get station globals
       m_oGlobals = gMainWindow.m_oEngine.NewPropertyObject( 3, False, "", 0); 
       m_oGlobals = gMainWindow.m_oEngine.Globals;
    and got the following error when I compiled:
      290, 39   Left operand of . has incompatible type 'CAObjHandle'.
    which referred to
    m_oGlobals = gMainWindow.m_oEngine.NewPropertyObject( 3, False, "", 0); 
    If anyone can help I'd greatly appreciate it.

    Hi there,
    The reason the code for TestStand globals does not work is because CVI does not support using the TestStand API in this way.  This can be a little confusing because in the help it lists using these methods and functions to access the properties you were looking for, however, in CVI you still have to use the TS_ functions to access different properties.  Usually it is TS_objectToOperateOn.  For example TS_Engine will always be getting properties or executing methods of the engine.  I have put some code below that should accomplish the same thing you were looking to do.  Hope this helps out!
        int error = 0;
        ErrMsg errMsg = {'\0'};
        ERRORINFO errorInfo;
        CAObjHandle myGlobals;
        //Get the globals from the engine
        tsErrChk (TS_EngineGetGlobals (myEngine, &errorInfo, &myGlobals)); 
        //Store the last user name into a local string
        tsErrChk (TS_PropertyGetValString(myGlobals, &errorInfo, "TS.LastUserName", 0, &lastUserName));
    Error: 
        // FREE RESOURCES
        if (lastUserName != NULL)
             CA_FreeMemory(lastUserName);
        // If an error occurred, set the error flag to cause a run-time error in TestStand.
        if (error < 0)
             *errorOccurred = TRUE;
            // OPTIONALLY SET THE ERROR CODE AND STRING
             *errorCode = error;
             strcpy(errorMsg, errMsg);
    Pat P.
    Software Engineer
    National Instruments

  • Accessing static variable using GWT remote servlet

    Hi all,
    Using GWT, I'm trying to call two methods which exist in a
    RemoteService from my entrypoint class.
    I have two methods within my remoteService servlet, method A and
    method B.
    Method A returns an int and sets an arraylist.
    Method B returns the arraylist, myList.
    I'm assuming that a single callback is associated with a single
    servlet method? Is it possible to access the arraylist, which has been
    set from calling method A, using the callback?
    e.g.
    //client code:
                   MyServiceAsync myService = (MyServiceAsync)
    GWT.create(MyService.class);
                   AsyncCallback callback = new AsyncCallback(){
                      public void onSuccess(Object result) {
                      public void onFailure(Throwable caught) {
                  myService.foo(callback);
    // servlet code
    public class MyServiceImpl extends RemoteServiceServlet implements
    MyService{
           public static List myList = new ArrayList();
           public int A(){
                   setB();
                   return 10;
           public void setB(){
                   // this adds five elements to a static arraylist, myList
           public List getB(){
                   return myList;
    }

    Ok, frist solution (the better one) is that You can create a class that will both contain the int and the list. E.g.
    public class MyObject implements Serializable {
    private int value;
    private List<Object> list;
    //getters and settersThen You can set the values You're interested in the RemotServiceServlet and simply return this object - aync callbacks can return various types of objects (not only primitives) but under two conditions:
    1) The object must implement the Serializable interface
    2) The object must have public no argument constructor or no constructor at all.
    Then in your client class You'll have:
    MyServiceAsync myService = (MyServiceAsync) GWT.create(MyService.class);
    AsyncCallback<MyObject> callback = new AsyncCallback<MyObject>(){
    public void onSuccess(MyObject result) {
      result.getList();
      result.getInt();
    public void onFailure(Throwable caught) {
    myService.A(callback);
    };The second solution is to invoke a method B callback in the result of A's callback:
    MyServiceAsync myService = (MyServiceAsync) GWT.create(MyService.class);
    AsyncCallback aCallback = new AsyncCallback(){
    public void onSuccess(Object result) {
       //here You get the in value
       AsyncCallback bCallback = new AsyncCallback(){
        public void onSuccess(Object result) {
         //here You get the list
        public void onFailure(Throwable caught) {
        myService.B(bCallback);
    public void onFailure(Throwable caught) {
    myService.A(aCallback);Hope this is clear and will help You. (Remember also the use generics!)

  • Access private variables from javascript

    Hi.
    How can i access my objects and varibles, in my java code from my javascript.

    Try displaying the value before you assign it.
    If you wanna display the value of a text field called textCallClass, this is the javascript code:
    alert(document.getElementById("form1:textCallClass").value);
    And if you wanna display a field called uniqueNum from a page called
    SchemeHolders, this is the javacsript code:
    alert(#{SchemeHolders.uniqueNum});
    You have ro have a public function called getUniqueNum in SchemeHolders.java. And ensure the case is exactly like mine is.
    That does work fine in my programs, if you have any other problems, post the error message.

  • Private variable issues

    Hello,
    While studying I have come up with this problem a few times and was wondering if you could help me.
    I am currently working with linked list examples and the variables used have default package access. I am however told that the variables should normally be declared private.
    So I made a kinda dummy class which shows my problem.
    public class Private
         private Private unreachable;
         private String greating="hello";
         public Private()
              unreachable = null;
              greating="";
         public String getGreating()
              return greating;
         public Private getReach()
              return unreachable;
    public class PrivateWork
         private String differentGreating;
         private Private reachMe;
         public PrivateWork()
              differentGreating="";
              reachMe=null;
         public void changeGreating(String change)
              Private p = new Private();
              p.greating = change;     //produces "greating has private access in the class Private" error
              p.getGreating() = change; //produces "unexpected type" error
              reachMe = p;
    public class TestPrivate
         public static void main(String[]args)
              PrivateWork p = new PrivateWork();
              p.changeGreating("Good Morning");
    }I know that by making the Private class an inner class of PrivateWork I can keep the variables declared private and the "p.greating = change;" will work.
    However is there another way I can access the "greating" variable from the changeGreating(String change) method in the PrivateWork class.

    I am currently working with linked list examples and the variables
    used have default package access.What variables are you referring to?
    p.greating = change;     //produces "greating has private access in the class Private" error That one should be pretty obvious because it is the definition of private: you can't use objects of the class to access private variables.
    By the way, "greating" is spelled greeting.
    p.getGreating() = change; //produces "unexpected type" errorI'm not sure about that one. But, you can split that statement up into two lines and you won't get a compile error:
    String gr = p.getGreating();
    gr = change;However, I don't think that is going to do what you expect. Try to predict the output of this example:
    class Private
         private String greeting="hello";
         public String getGreeting()
              return greeting;
    public class AATest1
         public static void main(String[]args)
              Private p = new Private();
              String gr = p.getGreeting();
              gr = "Goodbye";
              System.out.println(p.getGreeting()); //Output??
    }

  • About private variables

    Is there any way of accessing Private variables of a class into another class?

    The whole point of "private" is to make the variables private to the class. Your only sensible option is to use the "bean" standard, with setXXX() and getXXX() or isXXX(). For example:
    public class ABC {
        private boolean myLogic = false;
        private String myString = null;
        public boolean isMyLogic() {
            return myLogic;
        public void setMyLogic(boolean newMyLogic) {
            myLogic = newMyLogic;
        public String getMyString() {
            return myString;
        public void setMyString(String newMyString) {
            myString = newMyString;
    }Or, if side-effects are not a problem, just make the variables public.
    You may find the following links useful.
    http://java.sun.com/docs/books/tutorial/javabeans/index.html
    http://java.sun.com/products/javabeans/docs/spec.html
    Good luck!

  • Accessing session variables

    Hi ,
    I have session variable defined using portals (forms or plsql portlets).
    Can i access these variables using jsp portlets ??
    This is an urgent requirement ..
    Regards,
    Vijaya

    "145822",
    If your application with application id 100, for example, uses a common authentication scheme with application 200 (using the same cookie name in the case of an HTML DB style authentication scheme), then the two applications can run in the same session. A potential benefit of this, even if the two apps are not intricately related, is that the user has only to authenticate once per new session and will have access to both apps. If you set it up this way, then app 100 can access app 200's items in the same session using this function from within app 100:  htmldb.application.fetch_app_item(p_item=>'ITEM_NAME',p_app=>200);Scott

  • Accessing private attribute of a class from its Friend Class

    Hi Experts ,
    Please help me to understand how can i access private attribute of one class from its friend class.
    I am coding in Method (DO_SAVE) of class /BOBF/CL_TRA_TRANSACTION_MGR.
    I need to access private variable ( MO_BOPF) of class /BOBF/CL_TRA_SERVICE_MGR ( Friend of /BOBF/CL_TRA_TRANSACTION_MGR ).
    Regards,
    Reny Richard

    Hi Reny,
    You should be able to access by creating object of friend class.
    Sample:
    data lo_frnd     TYPE REF TO  /BOBF/CL_TRA_SERVICE_MGR.
    data lo_compl  type REF TO /BOBF/IF_TRA_TRANS_MGR_COMPL.
       create OBJECT lo_frnd
         exporting
                   iv_bo_key = '111'
                   IO_COMPL_TRANSACTION_MANAGER = lo_compl.
    "access the private object of friend class
       clear lo_frnd->MO_BOPF.
    Note: need to provide iv_bo_key & IO_COMPL_TRANSACTION_MANAGER while creating object.
    Hope this helps you.
    Regards,
    Rama

  • How to access private attribute of a class from its Friend Class

    Hi Experts ,
    I am coding in Method (DO_SAVE) of class /BOBF/CL_TRA_TRANSACTION_MGR.
    I need to access private variable ( MO_BOPF) of class /BOBF/CL_TRA_SERVICE_MGR ( Friend of /BOBF/CL_TRA_TRANSACTION_MGR ).
    Please help me to understand how can i access private attribute of one class from its friend class.
    Regards- Abhishek

    Hi Reny,
    You should be able to access by creating object of friend class.
    Sample:
    data lo_frnd     TYPE REF TO  /BOBF/CL_TRA_SERVICE_MGR.
    data lo_compl  type REF TO /BOBF/IF_TRA_TRANS_MGR_COMPL.
       create OBJECT lo_frnd
         exporting
                   iv_bo_key = '111'
                   IO_COMPL_TRANSACTION_MANAGER = lo_compl.
    "access the private object of friend class
       clear lo_frnd->MO_BOPF.
    Note: need to provide iv_bo_key & IO_COMPL_TRANSACTION_MANAGER while creating object.
    Hope this helps you.
    Regards,
    Rama

Maybe you are looking for

  • Control Panel text tool options switched places

    Hello there! Prologue: I've been searching for a solution for this problem and couldn't find any. Perhaps I don't know how to search properly. The problem itself isn't catastrophic yet it is really annoying to me, as I like to work quickly and everyt

  • Very slow external sata HD (lion)

    Hi everybody! It has been a while I am using a Netstor external HD (NR710C) 4x2TB WD Caviar black, RAID 10 (4TB total space, 2.71 Available, MacOS Extended Journaled). It is conntected with the MacPro (MacPro 4,1 - early 2009) via a Sonnet Tempo SATA

  • When i plug my ipod in itunes doesnt pop up what do i do?

    everytime i plug in my ipod it makes a sound letting me know it plugged in but it doesnt show up on itunes ! what do i do !?

  • Migrate development environment to Eclipse 3.4 M6

    I want to migrate development environment to Eclipse 3.4. I require to use version 2.1 of BEA Server Tools and want the download link for the same as I am using Eclipse 3.4 M6 and version 2.0 doesnt work with it. Any download link available for the s

  • Externally loaded swf in second window doesn't display properly?

    I have a bitmap based flash game (bitmapdata generated screen) that I'm trying to load in to a secondary nativewindow generated from a main flash (not AJAX/HTML)  based AIR app that's a graphical menu.  I.E. you click on a selection in the menu, and