Java reflection (interesting question)

hi folks,
class A {
void foo() {
Class B overrides method foo() in A
class B extends A {
void foo() {
Now i create a object of class B and assign to A
A aref = new B();
aref.foo() will call method foo()of class B. //polymorphism
Using reflection, is it possible to call method foo() of class A using the handle aref.
thanks
venkat

hi bondvenky,
What abt the answer for my original question. How to
access the base class methods using the handle for
child class object using reflection ?as far as i know, this isn't possible - your next question is probably going to be "why". It certainly seems slightly surprising that you can't do this, but you can access private methods. Unless you consider the latter a weaker way of breaking encapsulation (!?).
what was the sun's purpose behind allowing access to
the private methods of an object using Java
Reflection? good question.. its very useful but on the other hand i can't think of a time i've used it that couldn't be classed as a hack.
Is it not a security threat to java security model?it doesn't break anything - ie its not a security loophole. It links in with your question above though - would it have been possible/useful to not allow it period?
sorry for the vague answers :(
asjf

Similar Messages

  • Can Java reflect not only .Class file

    Hi' i'm newbie in this topic, i'm really appreciate if somebody can help me..cos i'm really stuck in here...
    My Problems are :
    1. i want to ask about this, can Java reflect from .java file?
    2. i'm using Eclipse IDE, i'm really interesting about how JTree or Package Explorer in Eclipse can always displaying update information about class structure? but .java files not compiled, how can? if Eclipse using reflection, .java files must be compiled first, correct me if i'm wrong?
    The fact is Eclipse don't have to compiled .java files to get the update information about class structure and displaying in JTree or package Explorer...how implement like this?
    what i mean like this :
    ex : if i type int x = 100; (not only int, it could be anything else..) at the working files, JTree or Package Explorer in Eclipse can always update the informasion about class structure, but .java files not compiled..
    i hope my question are easy to understand, i really need some help..
    Thanks a lot..

    hey, thanks for the answers, but i would like to ask :
    1) Eclipse performs background compilation of the Java sources, then performs reflection on those temporary classes++ if i'm using this way, how about the performance? seems that it will be compiled all the time right?
    2) Eclipse has access to the results of the Java source code parser, and can extract the information from the java syntax parser, before it gets to the compilation stage.++ how to implement this? what do you mean about java syntax parser?
    do you know where i can find any article about this?
    thanks a lot again...

  • Java Reflection and dynamic class loading

    I am trying to load my classes 'dynamically' using java reflection, which is a feature absolutely necessary for my webapp. I could not get this to work as of yet. Could someone please give me a piece of sample code that would do the following :
    - return the value (String) of known method y from class x
    - class x is only known at runtime (from the query-string in this case)
    - method y is known
    Thanks in advance.
    cheers,
         Tom
    PS: Please do not give me any links to tutorials/articles that do not do the EXACT thing that I asked for. Thank you.

    tried it, but it always gives me a MethodNotFoundException, because its trying to find my class in java.lang.String for some reason...
    heres part of the code (its an altered version of the code given in the invoke tutorial):
    public String getMethodReturnValue(String methodName, String className) {
    String result = null;
    Class theModuleClass = String.class;
    Class[] parameterTypes = new Class[] {};
    Method concatMethod;
    //Object[] arguments = new Object[] {parameters};
    try {
    concatMethod = theModuleClass.getMethod(methodName, null);
    result = (String) concatMethod.invoke(createObject(className), parameterTypes);
    } catch (NoSuchMethodException e) {
    result = e.toString();
    } catch (IllegalAccessException e) {
    result = e.toString();
    } catch (InvocationTargetException e) {
    result = e.toString();
    return result;
    private Object createObject (String className) {
    Object object = null;
    try {
    Class classDefinition = Class.forName(className);
    object = classDefinition.newInstance();
    } catch (Exception e) {}
    return object;
    Thanks for any help!
    -Tom

  • Java Reflection

    Hi Every1....i have a problem with java reflection n hope some1 will be able to resolve this me.
    I am getting the name of the child class as a string argument.
    eg String classname = this.getattributes().get("classname");
    I need to dynamically create the object of this instance using the classname and call a specific method...i know the name of the base class but the base class doesnt have the method i need....i m not allowed to redesign the base class...
    plz help

    but the problem is getting the method nameIf you don't have the method name what exactly is the plan? You've gotta have something ...
    .....i have the object of base class with meActually the object is an instance of the derived class ...
    ....and the method i
    need is in the child class.....so how do i invoke the
    method???Sigh. You can lead a horse to water but you can't make him drink. See
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object...)

  • Code generation through Java Reflection

    Hi
    I am after some clarification about the possibility of mapping of method outputs to other method inputs, using java reflection.
    The java objects are described in an XML based language (called DAML) as follows
    <java:Method rdf:ID="meth1" java:priority="1">
    <java:methodName>buildQuery</java:methodName>
    <java:parentClass>afsw.query.QueryBuilder</java:parentClass>
    <java:methodParameters rdf:parseType="daml:collection">
    <java:Parameter>
    <java:inORout>input</java:inORout>
    <java:type>java.util.Hashtable</java:type>
    </java:Parameter>
    </java:methodParameters>
    </java:Method>
    and I want to map them back to method calls and instantiations, so to be able to generate code on the fly. I need to know if its is possible to pass the output of a method such as getQuery() which in this case is a Document to the input of constructor MsgModule as in the following example:
    Document queryDoc =qc.getQuery();
    MsgModule mg= new MsgModule(queryDoc);
    regards
    Charlie

    This is possible. What you need to do in the 'new' instance case is to find the best constructor. So let's say you have Class clazz, the class you want to create a new instance of, and Class[] params, an array of objects to pass in the constructor. Using the Class api you can do:
    Constructor constructor = clazz.getConstructor(params);The getConstructor method will only return an exact match. Let's say one of the parameters was a subclass of an class that is allowable in the constructor. You can get all the constructors via clazz.getConstructors() and get all the parameters types via Constructor.getParameterTypes() and check to see if the params you passed in are compatible. You can use Class.isAssignableFrom() to help resolve this. Once you find the constructor, use Constructor.newInstance(params) to create the new instance. Hope this helps.

  • Java reflection and parameter's names

    hi, I have to extract from a method of a given class all types and names of the parameters, i've tryed to use java reflection function:
    Method[] metodo = temp.getDeclaredMethods();
    for (int i = 0; i < metodo.length; i++) System.out.println(metodo.toString());
    and the output is:
    public void DinamicLoad.function1.method1()
    public void DinamicLoad.function1.method2(java.lang.String)the function extract only the parameter's type, not his name

    Probabily all the "dozens, hundreds, thousands of
    other people who use reflection" knows very well
    classes that they use.
    Imagine to produce a class from a wsdl file, how can
    you know the content?
    How can you pass parameters if you know only the type
    and not the MEANING?When building classes from XML it's rare to use the constructor to convey the attributes, far more often each attribute is set independantly using a single argument setter with a signature like:
    public void setMyAttribute(String value) {Hence attribute names (e.g. myAttribute) are normally compared against method names, not parameter names.
    If constructors are to be used then parameters will be supplied in order.

  • Java reflection - any disadvantages

    1. Are there any disadvantages in using java reflection api (too much)?
    2. How do obfuscators deal with reflection based applications?
    Thanks
    Santosh

    Sorry, i wanted to know how the code
    Object obj = new MyClass();
    is different from
    Class clazz = Class.forName("MyClass");
    Object obj = clazz.newInstance();
    at the byte-code level.
    That is, in both the cases the classloader has to
    search for MyClass and invoke the constructor. Hope I
    am clear :)I don't think there is any difference as far as performance is concerned between the above mentioned methods for instantiating the object of MyClass.
    But here is what is generally said about using reflection(u can find it on google):
    ===============================================================
    Don?t overuse the Reflection API. Programs that use it are more difficult to understand and maintain. In addition, accessing fields and calling methods through the Reflection API is slower than using them in the ?normal? way, so use reflection only when it is really necessary.
    ===============================================================
    We too had concerns about reflection's performance, but as long as you cache the lookups, reflection is very fast. What is slow is doing things like looking up a method on a class or looking up an instance member. We do all these lookups once and then cache the results.
    ===============================================================
    Why is it slow as stated above? - Maybe because flexibility always comes at a price !!! Maybe the internal implementation of the call sequence by the JVMs is such that it cannot be implemented any faster...

  • Java reflection and singletons

    Using java reflection and singletons .. anyone seen this being used?

    I've solved it
    I had a singleton but then it turned out i had to use reflection instead, i tried to used reflection on 3 methods but the session value within was null upon the second method call. Relfection was re-creating the Object.
    Sorry for wasting your time.

  • Help need regarding Java Reflection

    I need help in programming the following:
    I have to generate a test Harness for OOP.This program that automatically tests
    classes by instantiating them, selecting methods of these instantiated objects randomly or
    using some criteria, invoking them, and using the returned values as input parameters to
    invoke other methods. I have to use Java Reflection for this and methods must be of generic type!
    For this
    I have to generate a tree of functions(say 2 or 3).The functions could be say:int f(int){} and int g(int){}. or Int f(String), String g(float),Float h(int)..I have to create a tree of these function set and traverse them in BFS or DFS and generate combinations of these functions keeping some upper bound for the number of functions genrated(10) and size of combinations of functions(say 5).The output of one function should be the input to other function(so recursive).If any combination failed,then record(or throw exception).This all should be done using java reflection.The input can be provided though annotations or input file.This file can result in recording even the output for each function. I have tried using Junit for testing methods.My code with is following:I have two classes ClassUnderTestTests(which tests the methods of ClassUnderTest) and ClassUnderTest shown below
    //Test Harness class
    public class ClassUnderTestTests {
         Field[] fields;
         Method[] methods;
         Method minVal;
         Method maxVal;
         Method setVal1;
         Method setVal2;
         Method getVal1;
         Method getVal2;
         Class<?> cut;
         ClassUnderTest<Integer> obj1;
         ClassUnderTest<String> obj2;
         @Before public void setUp(){
              try {
                   cut = Class.forName("com.the.ClassUnderTest");
              fields=cut.getDeclaredFields();
              methods=cut.getDeclaredMethods();
              print("Name of the CUT class >>"+ cut.getName());
              print("List of fields >>"+ getFieldNames(fields));
              print("List of Methods >>"+ getMethodNames(methods));
              //creating method objects for the methods declared in the class
              minVal=cut.getDeclaredMethod("minValue");
              minVal.setAccessible(true);
              maxVal=cut.getDeclaredMethod("maxValue");
              maxVal.setAccessible(true);
              setVal1=cut.getDeclaredMethod("setVal1", Comparable.class);
              setVal1.setAccessible(true);
              setVal2 = cut.getDeclaredMethod("setVal2", Comparable.class);
              setVal2.setAccessible(true);
              getVal1=cut.getDeclaredMethod("getVal1");
              getVal1.setAccessible(true);
              getVal2 = cut.getDeclaredMethod("getVal2");
              getVal2.setAccessible(true);
              } catch (ClassNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         @Test public void cutIntegertest(){
              //instantiating the class using the argument constructor for Object 1
              Constructor<?> constr1;
              assertNotNull(cut);
              try {
                   constr1 = cut.getDeclaredConstructor(Comparable.class,Comparable.class);
                   obj1=(ClassUnderTest<Integer>)constr1.newInstance(Integer.valueOf(102),Integer.valueOf(20));
                   assertNotNull(obj1);
                   print("The object of CUT class instantiated with Integer Type");
                   // invoking methods on Object1
              assertEquals(minVal.invoke(obj1),20);
              //Object x = minVal.invoke(obj1);
              print("tested successfully the min of two integers passed");
              assertEquals(maxVal.invoke(obj1),102);
              // maxVal.invoke(obj2);
              //print();
              print("tested successfully the max of two integer values" );
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    @Test public void cutStringTest(){
         assertNotNull(cut);
         Constructor<?> constr2;
              try {
                   constr2 = cut.getDeclaredConstructor(Comparable.class,Comparable.class);
                   obj2=(ClassUnderTest<String>)constr2.newInstance(String.valueOf(obj1.maxValue().toString()),obj2.minValue().toString());
                   //obj2=(ClassUnderTest<String>) cut.newInstance();
                   assertNotNull(obj2);
                   //assertNotNull("obj1 is not null",obj1);
                   //print(obj1.maxValue().toString());
                   print("Object 2 instantiated as String type ");
                   print("setting values on object2 of type string from values of obj1 of type Integer by using toSting()");
                   setVal1.invoke(obj2, obj1.maxValue().toString());
                   setVal2.invoke(obj2, obj1.minValue().toString());//obj2.setVal2(obj1.minValue()
                   assertEquals(getVal1.invoke(obj2),maxVal.invoke(obj1).toString());
                   assertEquals(getVal2.invoke(obj2),minVal.invoke(obj1).toString());
                   print("validating the Assert Equals set from object 1 after conversion to String");
                   print("MinValue for Object2 when Integer treated as String>>> "+minVal.invoke(obj2));
                   print("MaxValue for Object2 when Integer treated as String>>> "+maxVal.invoke(obj2));
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              //obj2.setVal1(obj1.maxValue()
         private static void print(String str){
              System.out.println(str);
         private String getMethodNames(Method[] methods) {
              StringBuffer sb= new StringBuffer();
              for(Method method: methods){
                   sb.append(method.getName()+ " ");
              return sb.toString();
         private String getFieldNames(Field[] fields) {
              StringBuffer sb= new StringBuffer();
              for(Field field: fields){
                   sb.append(field.getName()+ " ");
              return sb.toString();
    //ClassUnderTest
    public class ClassUnderTest <T extends Comparable<T>>{
         //Fields
         private T val1;
         private T val2;
         ClassUnderTest(){}
         public ClassUnderTest(T val1, T val2){
              this.val1=val1;
              this.val2=val2;
         * @return the val1
         public T getVal1() {
              return val1;
         * @param val1 the val1 to set
         public void setVal1(T val1) {
              this.val1 = val1;
         * @return the val2
         public T getVal2() {
              return val2;
         * @param val2 the val2 to set
         public void setVal2(T val2) {
              this.val2 = val2;
         public T maxValue(){
              T max=null;
              if(val1.compareTo(val2) >= 0){
                   max= val1;
              }else {
                   max= val2;
              return max;
         public T minValue(){
              T min=null;
              if(val1.compareTo(val2) < 0){
                   min= val1;
              }else {
                   min= val2;
              return min;
    This code throws Null Pointer Exception if CutStringtest function(I think on calling obj1 in tht function) Please suggest!

    Well, I can't help you specifically since I'm not into reflection too much, but here are some ideas:
    * Either learn how to set breakpoints and single step through your code, or pepper your code with a lot more meaningful System.out.println() statements.
    * Come up with simple test cases, pass them first, then progressively more complex test cases, until you test all possible situations. Try to get each test case to test only a single concept and not multiple concepts at the same time. If your code is broken on more than one concept, you will not be able to isolate each concept by itself to fix it without separating it.
    * Consider refactoring your code so each sub-module accomplishes one task in isolation and verify that module can handle each possible situation that its asked to perform.
    * The exception usually tells you what line in your code threw the exception. Look for a line in the exception printout that has the name of your package or class in it.

  • Performance difference between java.beans.Expression and Java Reflection

    What is the Performance difference between using java.beans.Expression class and Java Reflection classes like Class,Method ??

    negligible

  • Questions on Java Reflection in EJB

    Hi,
    Recently, I use reflection technology on EJB to get/set properties of a bean.
    We need it because we need to encapsulate data in a map to transfer data between
    presentation layer and business back end(i.e. the so-called value data object).
    A bean is packed into a map as following:
    The property name of a bean becomes the key in the map, and its value becomes the
    corresponding value in the map.
    So we have to do two things:
    1)Given a bean, convert it to a map;
    2)Given a data map, assign the value to a bean
    It would be nice if we can implement the two requirements in a base class. So I use
    reflection. And succeed to achieve the goal.
    But there are two problems occured and I can't understand why.
    1)If I use Class.forName() to load the entity bean implementation class(BMP or CMP abstract
    schema) I got a ClassNotFoundException. A workaround is to jar the BMP or CMP bean class
    and place it on the classpath.
    So, I want to know why there is such restriction.
    2)For the classes java.lang.reflect.Method, java.lang.reflect.InvocationTargetException
    I reference to in bean class, the IDE(I use IntelliJ Idea) give me a
    warning: "Use java.lang.reflect.Method are not allowed in EJB". Are the methods really
    dangerous in EJB environment?
    Can anyone explain me these pluzzles?
    Thank you in advance!
    BTW, I develop under weblogic 7.0. Now, my program functions well, I just can't understand
    the above phenomena.
    Regards,
    Justine

    1) You should never directly manipulate the EJB implementation class. That class is for the container. When accessing EJBs (no matter the means), you should use the Home/Remote or Local interfaces - those your client should already have. If what you're doing is actually working for you, I can only say that you're not using EJBs properly and are not getting the actual "bang for the buck" you paid for. And you're damn lucky it hasn't blown bits all over the place...
    2) Yes, it is potentially dangerous to be dorking around with reflection on EJBs. When you're using the Home/Remote or Local interfaces, you're actually using an Object that the vendor supplies to perform the actual remote operations. Using reflection could potentially invoke one of the "hidden" vendor methods with extremely unpredictable results - like deleting your entire table.
    As for using a map for transferring data, I would strongly recommend against it, especially in this case, because you've not only lost the strong typing you get with ValueObjects, but you have to do a lot of extra work on both "sides" (client and EJB) to make sure all your data is present and/or correct.

  • Interesting question in Java!!!!!!!!

    Hi,
    I am in need of getting some help on the following Java problem,
    I have a String variable with a value of,
    "if (flag) i=i+1 else i=i-1;" or "...some other arthmetic operation.."
    and at one poing of time i need to execute the code inside this String. Is there anyway? Pls do help me. Thanks in advance.
    Crao

    I don't know of anything that will handle both expression evaluation and program logic...
    http://www.beanshell.org/intro.html
    http://jep.sourceforge.net/

  • Question about java reflection and "int" type

    hi, using reflections I should invoke a Method (meth3) that have as parameter an INT type (not integer). I've tryed with this code:
                        int num = 3;
                        Class[] vettClax = {int.class};
                        Object[] vettParam = {num};
                        Method meth3 = temp.getMethod("meth3", vettClax);
                        meth.invoke(o, vettParam);My problem is that the int value is catched as an Integer value and reflection doesn't found a method that accept an INTEGER as parameter, who can help me?

    Works fine when I try it.
    public class t
        public static void main(String args[])
         throws Exception
         Class temp = t.class;
         t o = new t();
         int num = 3;
         Class[] vettClax = {int.class};
         Object[] vettParam = {num};
         Method meth = temp.getMethod("meth3", vettClax);
         meth.invoke(o, vettParam);
        public void meth3(int n)
         System.out.println("hello " + n);
    }Is your meth3() public?

  • Java/OO Design question.  Please help!

     

    Brian,
    I'd say your better off trying the
    weblogic.developer.interest.ejb newsgroup
    or alternatively try the discussion forums in
    www.theserverside.com
    or
    http://forum.java.sun.com/
    For what its worth I'd return an empty array rather than an exception as I associate
    exceptions with real errors whereas a search that happens to return nothing is a
    valid result.
    Cheers,
    mairt
    "Brian Snyder" <[email protected]> wrote:
    >
    I'm certain this is not the best forum for my question, but I didn't any
    other
    that seemed obvious.
    I have a design issue/ OO question. Our system has the very common requirement
    of searching. We have build a session EJB which actually performs the search
    and returns a collection of Value Objects back to the client. My question
    is
    this: If the search EJB finds no matching records, what is the correct
    strategy
    for dealing with it?
    1) Throw an application exception, such as "NoDataFound", which the client
    can
    catch and handle appropriately
    2) Simply return a null collection. In which case, the client will have
    to check
    for null, and redirect program appropriately.
    3) Simple return type, such as boolean, for the method -- indicating success
    or
    failure (meaning no records found).
    4) Something entirely different. If so, what?
    Your thoughts on this subject would be greatly appreciated!
    Thanks!
    Brian

  • Simple Java Network Programming Question

    import java.io.*;
    import java.net.*;
    public class ConsumerClient
         private static InetAddress host;
         private static final int PORT = 1234;
         private static Socket link;
         private static Resource item;
         private static BufferedReader in;
         private static PrintWriter out;
         private static BufferedReader keyboard;
         public static void main(String[] args)     throws IOException
              try
                   host = InetAddress.getLocalHost();
                   link = new Socket(host, PORT);
                   in = new BufferedReader(new InputStreamReader(link.getInputStream()));
                   out = new PrintWriter(link.getOutputStream(),true);
                   keyboard = new BufferedReader(new InputStreamReader(System.in));
                   String message, response;
                   do
                        System.out.print("Enter 1 for resource or 0 to quit: ");
                        message = keyboard.readLine();
         if(message.equals("1")**
                             item.takeOne();**
                        //Send message to server on
                        //the socket's output stream...
                        out.println(message);
                        //Accept response from server on
                        //the socket's input stream...
                        response = in.readLine();
                        //Display server's response to user...
                        System.out.println(response);
                   }while (!message.equals("0"));
              catch(UnknownHostException uhEx)
                   System.out.println("\nHost ID not found!\n");
              catch(IOException ioEx)
                   ioEx.printStackTrace();
              finally
                   try
                        if (link!=null)
                             System.out.println("Closing down connection...");
                             link.close();
                   catch(IOException ioEx)
                        ioEx.printStackTrace();
    }

    georgemc wrote:
    BlueNo yel-- Auuuuuuuugh!
    But the real question is: What is the air-speed velocity of an unladen swallow?

Maybe you are looking for

  • Open link in new window/tab

    Hello, is there anyone that can tell me how you can make a link to a webpage outside your wiki that opens in a new window or tab, so that the wiki stays open. thanks in advance...

  • PO Replication from SRM to ERP

    Hello, We replicate purchase orders from SRM to ERP.  Now we would like to make all of the contract data available for reporting in BW.  Would anyone know a bit more about how purchase orders are replicated from SRM to ERP?  The name of the program t

  • Table Value Set.

    Hi All, 1) I created a Table type value set for concurrent program. and i want a add one more value to value set, for that im using union clause in Where/order by Field.. ex code: Where/order by: where 1=1 union select 'ALL' name from per_all_positio

  • Upgrade from PS2 to PS5 on Mac

    How can I upgrade my Adobe Creative Suite 2 Premium to Photoshop 5 only on a new Mac Mini?  I only want the Photoshop to be upgraded, and the Mini does not have a CD drive (hence, an downloadable version is needed).  Please help before I take this Mi

  • CA asset deployment are got failed for all deployments

    CA asset deployment are got failed and getting the following exception 2011-11-17 17:10:42,434 INFO [nucleusNamespace.atg.epub.DafDeploymentOptimizerDeploymentEventListener] # assets <=100 2011-11-17 17:10:42,434 INFO [nucleusNamespace.atg.epub.DafDe