Use reflection to access static constant

I have a class with a static constant value. Can somebody show me to access the constant value using reflection.
Thanks
Regards,
Stephen

I have class
public class one{
public static final String TABLE_KEY = "something";
to access the class
one.class.getField(">>what to put here<<") it's static method don't hv any getter method???

Similar Messages

  • How to access private method of an inner class using reflection.

    Can somebody tell me that how can i access private method of an inner class using reflection.
    There is a scenario like
    class A
    class B
    private fun() {
    now i want to use method fun() of an inner class inside third class i.e "class c".
    Can i use reflection in someway to access this private method fun() in class c.

    I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
    Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
    So here's what it looks like:
            //list of inner classes, if any
            Class[] classlist = A.class.getDeclaredClasses();
            A outer = new A();
            try {
                for (int i =0; i < classlist.length; i++){
                    if (! classlist.getSimpleName().equals("B")){
    //skip other classes
    continue;
    //this is what I mention above.
    Constructor constr = classlist[i].getDeclaredConstructor(A.class);
    constr.setAccessible(true);
    Object inner = constr.newInstance(outer);
    Method meth = classlist[i].getDeclaredMethod("testMethod");
    meth.setAccessible(true);
    //the actual method call
    meth.invoke(inner);
    } catch (Exception e) {
    throw new RuntimeException(e);
    Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

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

  • Using static constants as id in FXML

    Is it possible to use a static constant as the id in FXML, and if so how ?
    For example if i have a class Person with a static constant defined, such as:
    static final String NAMEFIELD = "name";
    And then in an FXML file:
    <?import Person?>
    <TextField id=Person.NAMEFIELD />
    The above FXML code generates an error saying that an " is exspected.
    I've also tried with "$Person.NAMEFIELD" but that doesn't seem to work either.
    Any suggestions ?

    Is it possible to use a static constant as the id in FXML, and if so how ?Yes, this is supported in JavaFX 2.2:
    <TextField>
      <id><Person fx:constant="NAMEFIELD"/></id>
    </TextField>
    The above FXML code generates an error saying that an " is exspected.Quotes are required. FXML must be syntactically valid XML.

  • [svn:fx-trunk] 10891: Fix for ASDoc throws error when using getter methods for pseudo-inheritance of static constants

    Revision: 10891
    Author:   [email protected]
    Date:     2009-10-06 09:46:47 -0700 (Tue, 06 Oct 2009)
    Log Message:
    Fix for ASDoc throws error when using getter methods for pseudo-inheritance of static constants
    QE notes: None.
    Doc notes: None
    Bugs: SDK-22676
    Tests run: checkintests
    Is noteworthy for integration: No
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-22676
    Modified Paths:
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsDocUtil.java

    Have you tried using com.adobe.air.crypto.EncryptionKeyGenerator instead?

  • Working around unchecked conversions when using reflection

    I think I've convinced myself that there's no way around this issue when using reflection and Generics, but here's the issue:
    Suppose I've got a method that uses reflection to compare an arbitrary property in
    an arbitrary pair of beans (of the same class).
    public static <T> int compare(T bean0, T bean1, String prop) throws Exception {
         Method m = bean0.getClass().getMethod(
                   "get" + prop.substring(0,1).toUpperCase() +
                   prop.substring(1));
         Object o0 = m.invoke(bean0);
         Object o1 = m.invoke(bean1);
         if (o0 instanceof Comparable &&
             o1 instanceof Comparable &&
             (o1.getClass().isAssignableFrom(o0.getClass()) ||
              o0.getClass().isAssignableFrom(o1.getClass()))) {
              return ((Comparable)o0).compareTo(o1); // compiler warning
         } else {
              return o0.toString().compareTo(o1.toString());
    }There's no way that, in general, when using reflection to invoke methods, that you can coerce the types to avoid compile-time type safety warnings. I think the above code is guarranteed not to throw a runtime ClassCastException, but there's no way to write the code so that the compiler can guarrantee it. At least that's what I think. Am I wrong?

    Ok it looks like you're dealing with a classloader issue. when you call that method, it is the equivelant of calling
    Class.forName("Box", true, this.getClass().getClassLoader())The exception is thrown when your class's classloader cannot find the class box. try putting 'null' there
    Class.forName("Box", true, null)and it will request the bootstrap classloader to load the class. just make sure you have permission :
    If the loader is null, and a security manager is present, and the caller's class loader is not null, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the bootstrap class loader. (copied from the API)

  • Using reflection on passed classes

    Hello,
    I have been trying to write a common function to return the variables and values of a class passed into it. The function uses reflection to iterate through the Fields and returns a string of the variables and values. Is it anything to do with scope, as the same code works when I paste the method into the class I am looking at (See below)?
    I have pasted the code fragments below.
    Thanks
    stuart
    * Returns XML fragment of name value pairs of member/value
    * @param iClass the class under inspection
    * @return XML fragment of name value pairs of member/value
    public static String inspectMemberVariables(Class iClass)
    String oStr = new String();
    try
    Class c = iClass.getClass();
    Field[] f = c.getFields();
    System.out.println(f.length);
    for (int i=0; i < f.length; i++)
    // identify the field
    Field fld = c.getField( f.getName());
    //get the field name and grab the field value from the class
    oStr += f.getName()
    + "=\""
    + fld.get(c)
    + "\" ";
    } // for (int i=0; i < f.length; i++)
    oStr = "classname=\""
    + c.getName()
    + "\" "
    + oStr;
    } //end of try
    catch (NoSuchFieldException e)
    System.out.println(e);
    catch (SecurityException e)
    System.out.println(e);
    catch (IllegalAccessException e)
    System.out.println(e);
    } //end of catch
    return oStr;
    } // end ofinspectMemberVariables
    Where the code is called:
    public class ReflectionTest extends PPSpposEBCore
    public String strg;
    public ReflectionTest()
    String str2 = new String ();
    str2 = ClassProperties.inspectMemberVariables(this.getClass());
    System.out.println(str2);
    public static void main(String[] args)
    String str = new String ();
    try
    ReflectionTest rt = new ReflectionTest();
    // set dummy values to test
    rt.mPossessionId = 12;
    rt.mBusinessPossRef = "look it works";
    rt.mCreatedTs = new Date();
    //ClassProperties cp = new ClassProperties();
    //str2 = ClassProperties.inspectMemberVariables(rt.getClass());
    Class c = rt.getClass() ;
    Field[] f = c.getFields();
    System.out.println(f.length);
    for (int i=0; i < f.length; i++)
    // identify the field
    Field fld = c.getField( f.getName());
    //grab the field name and field value from the class
    str += f.getName()
    + "=\""
    + fld.get(rt)
    + "\" ";
    } // for (int i=0; i < f.length; i++)
    str = "classname=\""
    + c.getName()
    + "\" "
    + str;
    System.out.println(str);
    } //try
    catch (NoSuchFieldException e)
    System.out.println(e);
    catch (SecurityException e)
    System.out.println(e);
    catch (IllegalAccessException e)
    System.out.println(e);

    sorry it doesn't work, interface cannot have method body, i didn't know it. You couldn't access to private and protected datas with an exterior method. You can make a package with classes you want to inspect and a class who inspect. The classes of a package can access to protected datas.

  • Accessing static context from instances...

    Hello,
    I'm confused with something. Accessing static elemnts or static methods from an instance is allowed. I think it shouldn't be allowed. Because static context is class-wide so objects shouldn't be able to access them.
    Am I wrong..?

    I find it confusing.. If something is class-wide then
    it should only be accessed by the class, not the
    instance of the class...That depends on the nature or purpose of the information. Static information or methods are a useful way of sharing information between instances of the same class, while still having that information protected from other classes. Other examples are constants which are used within each instance. Why should each instance have a separate copy of exactly the same constant?
    You could even argue that any method which does not need any instance information should be declared static, but it is not always necessary to make that distinction.
    Eclipse (mine at least :) ) gives a warning when you access a static
    method/variable 'through' an instance, telling you that you should access >the method/variable in a static way.This warning usually occurs if you call a static method in a non static way. For example, if you declare a class called MyClass with a static method myMethod() and you have an instance assigned to variable anInstance, you should call the method using MyClass.myMethod() instead of anInstance.myMethod().
    Graeme

  • ** Not able to access Runtime Constants in ABAP XSL

    Hi friends,
    We have written one ABAP XSLT program. (XSLT program runs in ABAP Engine). This program is for the interface Mapping in XI. Source Interface occurrence is 1 and target interface occurrence is 0..unbounded. ie. We use Message Split to send source messages to multiple target messages. For this we have written one ABAP XSLT program. To find Value mappings we use 'SenderService' Runtime Constant to determine Sender Service (for Source Agency) at runtime. But the problem is,  inside template the constant $SenderService did not have the value.  I have given below the coding
    <xsl:param name = 'SenderService'/>
    <xsl:template match="/">
         <ns0:Messages xmlns:ns0="http://sap.com/xi/XI/SplitAndMerge">
                 <ns0:Message1>          
                  <ns1:employeeDemographicsRequest xmlns:ns1="http://aprilbiztec.com">
    <!-- here we are $SenderService did not receive the value -->
    Friends, Could you kindly help me to solve this problem ? (ie how to access Runtime Constants in ABAP XSLT when use message Split)
    Thanks in advance.
    Kind Regards
    Jeagthees P.
    Note :
    1) In normal ABAP XSLT, we are able to access Runtime Constant.
    2) For the same scenario, if we use normal XSLT ie. JAVA XSLT, we are able to access Runtime Constant.

    Hi,
    As far as I know you cannot access Runtime constants if there is a message split.
    Regards,
    Kumar

  • Using reflection...

    Hi,
    I have one class. to run that, I am calling like the following...
    java -classpath ;.;\comdotebo; com.pack1.MyClass
    now I want to take the reference of this class(dynamically) using reflection pakcage like the following...
    Class cla = Class.forName("com.pack1.MyClass");
    but to take the class reference I need to set the classpath;
    so how can i set the classpath dynamically.
    please give proper solution
    thanks
    Raja Ramesh Kumar M

    here the case is we know both the class and the class path at run time only
    for ex: see the following.....
    I have two files .....
    1) c:\dir1\com\pack1\MyClass1.class
    2) c:\dir2\com\pack2\MyClass2.class
    now I want to access both the classes using reflection from ...
    c:\dir3\com\pack3\MainClass.class
    using reflection, we can write the following...
    Class clas1 = Class.forName("com.pack1.MyClass1");
    if I am taking like this, then I am getting ClassNotFoundException.
    becoz, for that we have to give the proper classpath before running the program.
    like.
    set classpath=%classpath%;.;c:\dir1;
    but my problem is here I know the the class name (for ex: com.pack1.MyClass1) and the classpath (ex: c:\dir1)
    at runtime only.
    so please tell me how to solve this problem
    regards
    Raja Ramesh Kumar

  • Oracle proc Pro*C, g++/c++ compile error due to static const unsigned int sqlctx

    I'm using Oracle 8.1.6 for Linux, and 7.3.4 on HP-UX. Compiler is gcc/g++ 2.95.2
    In working with the Oracle precompiler on both HPUX and Linux, I've found a problem with the way that the Linux precompiler generates the sqlctx variable.
    On linux, the following is generated when you run the precompiler:
    static const unsigned int sqlctx = 1;
    However, on HPUX, this is the corresponding code:
    static unsigned long sqlctx = 10673468;
    When you compile the Linux version with g++/c++ or aCC, you get fatal errors of this nature:
    SQLSubsystem.cpp:562: passing `const unsigned int *' as argument 2 of `sqlcxt(void **, unsigned int *, sqlexd *, const sqlcxp *)' discards qualifiers
    Is there a way to force the output of proc to leave off the const?
    If you view the binary file proc, you can find the static unsigned int string listed. So I think it may be an option. However, I can't seem to turn it on.
    Thanks-
    Matt Wright

    As for sqlctx:
    sqlctx is a module identifier variable. i.e. if your project consists of multiple modules, each sqlctx should have different value.
    I have seen this error only on Linux Pro*C starting of 8.1.5 version (have not tested 8.0.5 nor 8.1.6).
    Anyway, I really can not understand why this error is not patched already.
    As for constness:
    I can not tell if there is an option which would solve such issue. I can only advise not to use -Werror option of gcc. It generates about 4-5 warnings per module, but it works ;-))

  • How To: Use reflection to create instance of generic type?

    I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
    My first guess was to write the following:
    Class cls = Class.forName("java.util.ArrayList<String>");
    List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
    Class cls = Class.forName("java.util.ArrayList");
    List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
    If I change the second line to
    List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
    This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
    Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?

    Harald,
    I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
    I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        for ( ...whatever ...) {
           T obj = clazz.newInstance();
           // code to load from storage ...
           list.add(obj);
        return list;
    }And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
    I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
       private static Map<String, Class<? extends Base>> classMap = null;
       static
          Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
          classMap = Collections.synchronizedMap(map);
       public static Class<? extends Base> getClass(String name)
          return classMap.get(name);
       protected static void putClass(Class<? extends Base> cls)
          classMap.put(cls.getName(), cls);
    }And added a static initializer to each of my persistent classes:class Foo extends Base
       static
          Base.putClass(Foo.class);
    }So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
    Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
    Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
    Thanks again for your help,
    Gary

  • Accessing Runtime Constants in PCK

    Hi all
    Anybody tried accessing runtime constants such as message ID  in PCK, successfully?
    I have written a java mapping using StreamTransformationConstants class to retrieve MessageId value. The same java mapping works fine in XI, but not PCK.
    Any idea?
    Many thanks.
    YJ

    to the target  date mapping we have created a userdefined fuction fileName which is failing the error message when we  test the interface mapping is Runtime exception occurred during execution of application mapping program com/sap/xi/tf/_XI_ERP_FI_BAPI_ACC_DOCUMENT_POST_REQ_MM_: com.sap.aii.utilxi.misc.api.BaseRuntimeException; RuntimeException in Message-Mapping transformation: Runtime exception during processing target field mapping /ns1:BAPI_ACC_DOCUMENT_POST/DOCUMENTHEADER/HEADER_TXT. The message is: Exception:[java.lang.NullPointerException] in class com.sap.aii.mappingtool.flib3.TextFunctions method substring[null, com.sap.aii.mappingtool.tf3.rt.Context@0000000000000]
    is this help full
    when it is succesfull the input <HEADER_TXT>Payroll for 01/2008</HEADER_TXT>
    <DOC_DATE>20080131</DOC_DATE> 
                                                    when it is failed the input is
    <HEADER_TXT>Payroll for 20/08.t</HEADER_TXT>
    <DOC_DATE>08.t20</DOC_DATE>
    thanks and regards
    sandeep
    thanks
    sandeep

  • Problem using reflection... Really urgent...

    Hi all,
    in my current program, i'm usin reflection a lot. This is due to the fact that i automatically generate some code, compile it, and run another program which uses the generated code.
    The generated code contains inner classes. For example:
    package mypackage;
    class A {
    public A() {}
    class B {
    public B() {}
    class C {
    public C() {}
    My question is: how can i instantiate, the classes B and C using reflection? i think i tried everything but when i run my prog i keep having error messages such as:
    - InstantiationException
    - NoSuchMethodException
    -etc...
    Any idea?
    Jack

    Consider this:
    Can you make the inner clases static? If you do, you may instatiate them by using names like A.B and A.B.C.
    If the inner classes are not made static, they need an instance of the enclosing class in order to be instantiated. This basically means that you may instantiate a B from inside a (non-static) method (or constructor) in A, and a C from within a method in B.
    One way of doing this is to create a method on A that creates a B (a factory method). Then, in order to get a B you first create an A, then call the factory method to get a B. By putting a factory method for C's in B, you could then go on to create a C from the B.
    But before going into this, you should consider whether you really need the inner classes to be non-static.

  • Update problem when using reflection

    We have an issue when updating objects. The values are not updated in the DB when we set the values in the domain class using reflection. However when we explicitly set the values using the setter methods, update is ok.
    Here is the code for the reflection mechanism:
    UnitOfWork uow = session.acquireUnitOfWork();
    //domain class which needs to be persisted
    Student student = new Student();
    //get the clone
    Student studentClone = (Student) uow.registerObject(student);
    //copy the values from the value object into the
    // domain class using reflection
    studentClone.setVo(studentVo);
    uow.commit();
    The setVo method uses reflection to set the values (using invokeMethod). The values are set properly in the domain object. But the values are not updated when we do the commit.
    However, if we explicitly set the values in the clone using the "setter" methods, update is okay. So this code works fine.
    UnitOfWork uow = session.acquireUnitOfWork();
    Student student = new Student();      
    Student studentClone = (Student) uow.registerObject(student);
    studentClone.setName("NBA"); //set the value of name
    uow.commit();
    Any ideas would be appreciated...
    Thanks much

    TopLink 10.1.3 tracks changes through working and backup copies by default, so even if you set your changes through reflection they should be picked up. If you were using CMP 2 or EJB 3 or explicitly enabled AttributeChangeTracking, then changes set through reflective field access could be missed. In this case you should use the set methods through reflection, instead of the field directly.
    I would check your code that set the changes through reflection, perhaps it is not working as you expect. Check the state of the object after applying the changes and verify they were actually set. Also ensure that you are changing the UnitOfWork clone, not the original object.

Maybe you are looking for

  • Can there be buttons/links on or in flash object?

    Hi, I have no idea how to ask this question properly. I am only designing this, not making it, so simple answers for me would be good, but also technical answers that I can pass on to the flash person. On my home page, I am going to have 3 images tha

  • Create a xml file from an internal table: CALL TRANSFORMATION

    Hello gurus, I want to create a xml file using data from scustom table. I will create an internal table and will select some records to it. I searched the forum and i discovered the call transformation, but when i execute the example program at the C

  • EJB - JAR or EAR file reloading - how to get it to work consistently.

    We are using wl 6.0 sp2 rp2 - with 2 WL instances on the same box. We have always seemed to have had this headache with WL - getting EJB's to reload consistently. Does anyone have a sequence of steps they follow to get good consistent reloading resul

  • Migration Assistant can't find my hard drive - can you help?

    Hi, I've just bought a new MacBook Pro (Lion) as my 6 year old iMac (Snow Leopard) has died. I wanted to restore my data from my iMac, via my Time Machine back-ups which are stored on a WD MyPassport. When using the migration assistant, I've followed

  • Java.sql.SQLException: Invalid column index: prepare_for_new_get

    I wrote a small test jsp which gets a DB connection using Oracle 816 type 4 JDBC driver. I have a procedure in the database defined as SQL> desc one PROCEDURE one Argument Name Type In/Out Default? ID NUMBER IN/OUT My jsp code does the following... s