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

Similar Messages

  • 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

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

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

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

  • In Office 2011 the function "share it by e-mail" seems to be disabled. that happened recently, just after the apple update regarding Java. Any idea on how enable this function again?

    in Office 2011 the function "share it by e-mail" seems to be disabled. that happened recently, just after the apple update regarding Java. Any idea on how enable this function again?

    I was able to get to a support person who helped me fix this without charge. I guess it was my bad for not trying the right way to access support.
    Anyway, they answer is this.
    I had to create a new account on my computer. When I logged into the new account it immediately wanted an AppleID. I used my daughter's e-mail address for the AppleID. This setup the internet accounts correctly with her iCloud.com e-mail address. I was then able to access e-mail in both the browser and Mail. Not that complicated but nothing that I would have easily thought up on my own.
    Thank Apple Support!

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

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

  • I am new to Java, can any one pls tell me what exactly is "Build Path".

    Hi Techies...
    i am new to Java, can any one pls tell me what exactly is "Build Path".
    thanx in adv.
    Regards
    Nitin.V
    Edited by: Nitin.V on Feb 12, 2008 11:08 PM
    Edited by: Nitin.V on Feb 12, 2008 11:09 PM

    The "BuildPath" is a place where all the "resources" referenced by your java program exists.
    please visit http://www.u.arizona.edu/~jtmurphy/H2R/java.htm for more info

  • HT201250 Is there any disadvantages to Time Machine? Why doesn't everyone get it?

    I am looking at Time Machine, and it looks great and really helpful. Are there any disadvantages? Why would anyone not get it? I am trying to figure out if I am missing something. Thank you!

    Unlike Mr. Galt, I don't use TM, preferring bootable clones made with Carbon Copy Cloner. Disadvantages?
    1. not bootable, so useless if the boot volume goes south, without reinstalling the OS and hoping that restores the boot volume. Alternatively, you can wipe the boot volume, reinstall the OS, and hope the TM backup is restorable. Contrast with booting into a clone and immediately knowing if it works. If so, then you're back in business.
    2. TM requires always having the ext HD connected and powered up. I prefer connecting ext FWHDs and updating clones on my schedule, not Apple;'s,
    3, I've never had to retrieve something I changed or deleted, so TM holds no value for me.
    To each their own. For more on TM vs clone, see http://pondini.org/TM/Clones.html
    Finally, a google search for TM vs clone gives many hits. Peruse them.

  • Hover Top Level Navigation, any disadvantages?

    Hello,
    I am considering .<a href="http://help.sap.com/saphelp_nw04/helpdata/en/53/a16a3e54a2e946e10000000a114084/content.htm">Setting Hover Effect (help.sap.com)</a> in the TLN, but I want to know if anyone has discovered any disadvantages with doing this e.g degraded performance or any other things.
    Best regards,
    Joe

    Dear Atul,
    Thank you for your quick reply.
    However, using horizontal-y is not serving my purpose. I want the functionality similar to that of the standard SAP TLN in case of the scrolling bar when the number of roles increase in TLN.
    Can you plz help me in writing the code for the same.
    Thank you,
    Regards,
    Disha.

  • 3.0 over 2.66 any disadvantage

    Other than the obvious cost difference is there any disadvantage getting the 3.0.
      Mac OS X (10.4.8)  

    You will find that if you bought 8GB RAM (4 x 2GB) and 3TB (4 x 750GB) of drives from 3rd party suppliers yourself you'd probably save enough to essentially get the 3GHz upgrade for "free". Not to mention you'll have the choice of which components you want.

  • FCP 6-Working with DV, any disadvantages to H.264 export?

    I am working in DV, I want to reduce final files size by exporting using Quicktime Conversion> H.264, I want to know if there are any disadvantages to using this codec for the final exported file?
    Thank you,
    Sebastian

    IT is perfect as your final export type. Nothing wrong with it.
    Shane

Maybe you are looking for

  • How to change email on apple tv

    I want to use another email for apple tv instead of sharing how can I change accounts

  • Displaying image in report

    I'm new to CF Report Builder and having trouble determining how to get a dynamic image to display in the detail band. The query for the report correctly returns the image file name, but the following expression doesn't display the image although the

  • Automatic tester user gets disabled in ISE

    We have ise1.2 working in our environment. For some reason the radius test user used for NAD device authentication gets disabled automatically. Though i couldnt get the frequency of it neither the timing of it. Any specific setting i am missing here

  • E-mail PROBLEM:  I get this: Reason: Error in sieve filter: Too many notifys specified

    I am using a MacBook Pro and an iPhone.  I always had success in getting e-mails pushed to the phone.  Suddenly, every time I receive an e-mail, I get another one from the postmaster saying: Reason: Error in sieve filter: Too many notifys specified.

  • Want to install ios 7.1.2

    hello, i have a ipod touch 5 and it have ios 7.0.6 installed, i want to install ios 7.1.2 and not the lastest and bugged ios 8, itunes says : error 3194. i have checked all posibilities from internet, and the hosts file is clear. what can i do now ..