Reflective Method Invocation

can someone please explain this concept to me? may be with some code. apparently java 1.4 is much more efficient at this.
thanks,
erik

Take a look at this Sun Java tutorial trail:
http://java.sun.com/docs/books/tutorial/reflect/object/invoke.html

Similar Messages

  • How to solve the "Method invocation failed" error in script?

    Hello,
    I'm trying to modify the script that enumerates all the txt (csv) files on folder and deletes empty columns, but with no luck. The script is working when I execute it on single csv file. But when I put script on loop, it generates errors:
    Method invocation failed because [System.Management.Automation.PSCustomObject] does not contain a method named 'split'.
    At C:\scripts\populate.ps1:25 char:1
    + $b = $line.split(",")
    + ~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (split:String) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound
    The script looks the following:
    $files = Get-ChildItem C:\scripts\Results\csv\* -include *.txt
    #Process files by performing a search and replace
    foreach ($infile in $files)
    $infilen = 'C:\scripts\Results\csv\'+[io.path]::GetFileName($infile)
    $infile = import-csv $infilen
    ##remove blank coloumns##
    $cStore = @() # array to store used column numbers
    $rNumber = 0
    foreach ($line in $infile)
    if ($rNumber -eq 0)
    {# ignore header
    else
    $b = $line.split(",")
    $fieldNum = 0
    foreach ($field in $b)
    if ($field -ne '')
    if ($cStore -notcontains $fieldNum) {$cStore += $fieldNum}
    $fieldNum += 1
    $rNumber +=1
    # array $cStore now contains column numbers with values
    $cStore = $cStore | sort
    foreach ($line in $infile)
    $nLine = ""
    $c = $line.split(",")
    foreach ($ar in $cStore)
    $nLine += $c[$ar]+","
    # remove trailing ,
    $nLine = $nLine.Substring(0, $nLine.Length-1)
    $fnFriendly = [io.path]::GetFileNameWithoutExtension($infile)
    $result=$fnFriendly+'cl.txt'
    Write-Output $nLine >> $result
    Also I have found the explanation on this error on this
    link but it seems this is not the case.  Can you help to solve this?
    Thanks!

    You are importing a CSV file which implies that you are creating an object (pscustomobject) and each item in that object is represented by $line. The issue is that this $line has multiple properties (for each column of the CSV) that you need to decide
    on which one to split:
    $c = $line.propertyname.split(",")
    I'm not sure, but it seems that if you are trying to split by a comma, then maybe you are assuming that you did something similar to a
    get-content on the file in which the original approach that you have done would work.
    Boe Prox
    Blog |
    Twitter
    PoshWSUS |
    PoshPAIG | PoshChat |
    PoshEventUI
    PowerShell Deep Dives Book

  • Why must this method invocation be caught?!

    Hi there. I have this following piece of code:
    public class Dog extends Animal {
         public static void main(String[] args) {
              Animal animal = new Dog();
              System.out.println(animal.getAge(args[0]));
         int getAge(String arg) {
              return Integer.parseInt(arg);
    class Animal {
         int getAge(String x) throws Exception {
              return 5;
    }Ok, I compiled this an received this notification from the compiler:
    Dog.java:4: unreported exception java.lang.Exception; must be caught or declared
    to be thrown
                    System.out.println(animal.getAge(args[0]));
                                                    ^
    1 errorIm a little confused here as to why I am receiving this notification...
    The reason being is firstly I thought that when you override a method you can declare fewer or narrower checked
    exceptions than the method that is being overridden and secondly,
    this is a polymorphic method invocation on line 4 as Dog's getAge method is being called,
    not class Animal's getAge method.
    Any clarification would be well received,
    thank you indeed.
    Edited by: shamrock08 on May 6, 2008 10:23 AM
    Edited by: shamrock08 on May 6, 2008 10:23 AM

    shamrock08 wrote:
    BigDaddyLoveHandles wrote:
    you don't get that compile-time error. Why do you get it with the first code? In expression animal.getAge(args[0]), variable animal is of type Animal, and Animal's getAge method signature includes "throws Exception". Typing is done statically, at compile-time, hence the syntax error.Im not sure im entirely understanding.
    I thought that in relation to overridden instance methods, the Object type determines which method
    will be invoked at runtime. Yes.
    So in this case wont the Dog getAge method be invoked? Yes.
    Im just a little confused as my book says that
    when a method overrides an inherited instance method it can declare fewer or narrower checked exceptions,
    Thanks for the input & regards.That's also true. I think what you are missing is the realization that compiler errors are based on static type information not runtime information.
    Consider this method:
    void f(Dog d, Animal a) {
        d.getAge("");
        a.getAge("");
    }The method invocation d.getAge("") doesn't throw Exception, because that is how you overrode getAge in class Dog.
    The method invocation a.getAge("") may throw a checked exception, because that is how the method is defined in class Animal. So the compiler will complain about this line: either catch or propagate the exception. Note that this compiler error is independent of what object a refers to -- a could be pointing to a Dog, it doesn't matter. Only the static typing matters at compile-time.

  • Error sending method invocation request(oc4j 10g(10.1.3.1))

    Dear,
    I have two applications a.ear and b.ear. They both are deployed on same oc4j container (10g(10.1.3.1))
    Both applications use each others session beans. In order to make communications between these two applications possible I set global-jndi-lookup-enabled attribute in <application-server> element in server.xml file, to be true.
    One of the applications use hibernate 3.1. According to some of posts from your forum, I replaced antlr.jar from toplink\jlib folder with one form with the one provided by the Hibernate 3 distribution.
    In order to integrate Hibernate with Container managed transactions, I set in hibernate.cfg.xml:
    hibernate.transaction.factory_class parameter to: org.hibernate.transaction.CMTTransactionFactory and
    hibernate.transaction.manager_lookup_class to: org.hibernate.transaction.OC4JTransactionManagerLookup.
    Everything works well since I save/update data in database. I save or update data, calling method from remote session bean.
    I am getting java.lang.NullPointerException. Here is my error log:
    2007-02-23 13:03:32.687 WARNING J2EE EJB-08002 [WorkflowManager] thread HTTPThreadGroup-12 encountered an exception while trying to end the transaction: oracle.oc4j.rmi.OracleRemoteException: An exception occurred during transaction completion: ; nested exception is:
    javax.transaction.RollbackException
    WARN processException, Unhandled Exception thrown: class com.ed.ecomm.edcore.exception.RepException
    2007-02-23 13:03:32.750 ERROR ServletException cause
    mermig > 13:03:32.765 ERROR SecurityFilter - EXCEPTION:
    Error sending method invocation request; nested exception is:
    java.lang.NullPointerException
    javax.servlet.ServletException: Error sending method invocation request; nested exception is:
    java.lang.NullPointerException
    at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:516)
    at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:423)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:226)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
    at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:397)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:64)
    at oracle.security.jazn.oc4j.JAZNFilter$1.run(JAZNFilter.java:396)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAsPrivileged(Subject.java:500)
    at oracle.security.jazn.oc4j.JAZNFilter.doFilter(JAZNFilter.java:410)
    at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:621)
    at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:368)
    at com.evermind.server.http.ServletRequestDispatcher.unprivileged_forward(ServletRequestDispatcher.java:259)
    at com.evermind.server.http.ServletRequestDispatcher.access$100(ServletRequestDispatcher.java:50)
    at com.evermind.server.http.ServletRequestDispatcher$2.oc4jRun(ServletRequestDispatcher.java:193)
    at oracle.oc4j.security.OC4JSecurity.doPrivileged(OC4JSecurity.java:283)
    at com.evermind.server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:198)
    at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1056)
    at org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:261)
    at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:388)
    at org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:316)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:231)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
    at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:397)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:64)
    at com.ed.mermig2plus.web.filters.AuthorizationFilter.doFilter(AuthorizationFilter.java:115)
    at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:15)
    at com.ed.ecomm.edcore.web.filters.MonitoringFilter.doFilter(MonitoringFilter.java:180)
    at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:17)
    at com.ed.ecomm.edcore.web.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:93)
    at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:17)
    at com.ed.ecomm.edcore.web.filters.DoFilterPrivilegedAction.run(DoFilterPrivilegedAction.java:65)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:320)
    at com.ed.ecomm.edcore.web.filters.jaas.OracleJAASProvider.performAction(OracleJAASProvider.java:166)
    at com.ed.ecomm.edcore.web.filters.SecurityFilter.performAction(SecurityFilter.java:595)
    at com.ed.ecomm.edcore.web.filters.SecurityFilter.doFilter(SecurityFilter.java:292)
    at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:17)
    at oracle.security.jazn.oc4j.JAZNFilter$1.run(JAZNFilter.java:396)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAsPrivileged(Subject.java:500)
    at oracle.security.jazn.oc4j.JAZNFilter.doFilter(JAZNFilter.java:410)
    at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:619)
    at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:368)
    at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:866)
    at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:448)
    at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:216)
    at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:117)
    at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:110)
    at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
    at oracle.oc4j.network.ServerSocketAcceptHandler.procClientSocket(ServerSocketAcceptHandler.java:239)
    at oracle.oc4j.network.ServerSocketAcceptHandler.access$700(ServerSocketAcceptHandler.java:34)
    at oracle.oc4j.network.ServerSocketAcceptHandler$AcceptHandlerHorse.run(ServerSocketAcceptHandler.java:880)
    at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:298)
    at java.lang.Thread.run(Thread.java:534)
    Can you help me? I can not find anything about this exception
    The same works for me in 10.1.2.0.2
    Thanks and regards,
    -- Smiljka

    OC4J can work with many different DataSources implementations to work against many different databases. We have not hardcoded it work only against an Oracle database. We have reworked the Data Source area in 10.1.3 to make it simpler and more consistent.
    I'd recommend having a read of the the J2EE Services Guide for 10.1.3 (http://download-west.oracle.com/otn/java/oc4j/1013/doc/web.1013/b14427.pdf)
    and have a look at chapter 4 where our new and improved DataSource implementation s discussed.
    -steve-

  • Using java.lang.reflect.Method.invoke on a static method?

    This is probably a FAQ, but I am finding it impossible to construct a search which answers this question for me.
    How do I call java.lang.reflect.Method.invoke on a static (e.g. class) method? Is it even possible?
    Thanks,
    dwh

    Is this of any help?
    http://www.esus.com/javaindex/j2se/jdk1.2/javalang/reflection/reflection.html
    Cheers,
    Joris

  • Detecting the source of a method invocation.

    Within a given method, is there a way to detect what class/method made the invocation call?
    I need to find a way to modify instance variables within a method, based on the invoking class ... I thought of navigating back through the Stack, but I am working with a multi-threaded application so I fear that I cannot absolutely depend on the last Stack call being the actual invoking class/method. Any ideas? - please help.
    Many thanks,
    Thomas

    How does one access the method invocation stack?I'm not sure if an easier way exists, but you can extend SecurityManager to fetch the Class context of the current Thread, which will provide you with an array of Class obejcts, ordered according to the method invocation stack. Thus, you can determine what Class invoked a particular method, but you can not determine what Object (not via the SecurityManager funcationality).
    Here is a simple class I often use for such a need (excuse any formating issues- or misspellings in the documenation)... ... although, it should be stated, this class may not work in certain environments- specifically ones that deny permission "createSecurityManager".
    * This class provides static utility methods for retrieving information
    * on the class context.  The methods in this class can provide a
    * resource with a list of the classes that invoked it, thus allowing
    * clases to determine if a particular method is being accessed by
    * the proper caller or allow Class variables to be initialized statically,
    * with out having to instantiate the type.
    * <p>This class is meant to provide simple functionality in familiar
    * environments.  Its funcationality may not work properly when executing
    * in an enviroment with strigent security permissions.  Specifically, if
    * permission is denied to construct a new SecurityManager instance, the
    * methods of this class will fail.
    * @author: Sean Flanerry
    public final class ClassLookup extends SecurityManager {
      private static final ClassLookup instance = new ClassLookup();
      private ClassLookup() { }
      * This method returns the class context for the current thread in format
      * <ul>
      * <li>Class for currently executing method
      * <li>Class that invoked the above method
      * <li>Class that invoked the above method...
      * </ul>
      * The first two elements in the returned array will be of type ClassLookup.
      * @see java.lang.SecurityManager#getClassContext()
      public static Class [] fetchClassContext() {
        return instance.getClassContext();
      * This method returns the Class that invoked this method.  This method
      * is used primarily by static initializers that have to retrieve a handle
      * to the java.lang.Class instance that wraps the current type, but that
      * can not instantiate the current type, eg <br>
      * <code>public static final Class currentClass = ClassLookup.getCallingClass();
      public static Class getCallingClass() {
        return instance.getClassContext()[3];
      * This returns the Class that invoked the current method on the calling
      * Class.  If for example, Race.startRace() invokes Runner.sprint(), Runner.sprint()
      * can determine what class invoked it by calling this method.  In other
      * words, this method lets other methods determine which class invoked
      * it.
      * <p>Remember that this method returns a Class instance for which
      * ever type contains the method which invoked the caller so the
      * Object returned by this method might be the caller's type if the
      * caller was spawned by a method with in the same class.  Consider,
      * <ul>
      * <li>Race.start() invokes
      * <li>Runner.sprint() which invokes
      * <li>Runner.fatigue()
      * </ul>
      * If Runner.fatigue() invokes this method, an instance of Runner.class will
      * be returned, <b>not</b> Race.class because fatigue was invoked by sprint.
      * <p>This method is typically used by resources that wish to determine
      * if the current method is being invoked via the proper context, ie the
      * invoking class is a trused resource.
      public static Class getInvokingClass() {
        return instance.getClassContext()[4];
      public static void main(String args[]) {
        Class [] c = fetchClassContext();
        for (int i = 0; i < c.length; i++) {
          System.out.println(c.getName());

  • Reflecting methods of parent class

    I have a class named ParentClass with a public method named getName that takes a String as a paramenter and returns a String.
    If I extend ParentClass, how can I use reflection to access the getName method of the parent (super) class? I get a NoSuchMethodException if I try to get the subclass to reflect any methods it inherits from its parent.

    Also ,I modified the above example to print the method return value . It work fine.
    import java.lang.reflect.Method;
    public class TestReflection {
         public static void main(String[] args) throws Exception{
              SubClass cls = new SubClass();
              Method m = cls.getClass().getMethod("getName", new Class[] {String.class});
              System.out.println(m.invoke(cls,new Object[] {new String("testing name")}));
    class ParentClass {
         public String getName(String s) {
         return s;
    class SubClass extends ParentClass {}

  • Trouble in dynamic method invocation

    hai forum,
    Your previous responses on this topic 'method invocation' has greatly helped me in writing a code to invoke method dynamically.As some experts pointed out,the parameters had to be type casted.
    Please help me out of my latest trouble.I invoke only a particular method 'methodName' of a particular calss instance 'instance'.But when i run the code Exceptions are thrown for all the methods of that class whereas i require exceptions connected with "methodName" only.
    I just could not figure out my mistake, so please help me out.
    Thank you.
        private class MethodInvoke implements ActionListener
            private String methodName=""; //name of the method
            Object instance;                          //instance of the class
            private int paraNum=0;             //num of parameters
            public void setParameters(String methodName,Object instance,int paraNum)
                this.methodName = methodName;
                this.instance=instance;
                this.paraNum=paraNum;
            public void actionPerformed(ActionEvent e)
                 try
                           //TAKE PARAMETERS FROM USER USING TEXTFIELDS INTO AN ARRAY LIST
                        Component[] cList = textfieldPanel.getComponents();
                        ArrayList parameterList = new ArrayList(paraNum);
                        Object[] parameters = new Object[parameterList.size()];
                         for (int x = 0; x < paraNum; x++)
                                if (cList[x] instanceof JTextField)
                                    String value = ((JTextField) cList[x]).getText(); 
                                    parameterList.add(value);
                        Method[] allMethods = instance.getClass().getMethods();
                        Method method = null;
                        for (int i = 0; i < allMethods.length; i++)
                                if (allMethods.getName().equals(methodName))
    method = allMethods[i];
    break;
    if (method == null)
    throw new RuntimeException("Method not found");
    Class[] types = method.getParameterTypes();
    for (int i = 0; i < paraNum; i++)
    String values = (String)parameterList.get(i);
    if (types[i].equals(Integer.class))
    parameters[i] = new Integer(values);
    else if (types[i].equals(Long.class))
    parameters[i] = new Long(values);
    else if (types[i].equals(String.class))
    parameters[i] = values;
    else if (types[i].equals(Float.class))
    parameters[i]=new Float(values);
    else if (types[i].equals(Boolean.class))
    parameters[i]=new Boolean(values);
    else
    System.out.println("Do not support the data type");
    Object result = method.invoke(instance, parameters);
    System.out.println("Invoked result: " + result);
    catch(Exception e3)
    System.out.println(e3);

    This is the Emp class which iam calling.Hope this will help you.
    import java.io.*;
    public class Emp
         private String designation;
         private int salary;
         private int id;
         private String name;
         public Emp()
         public void setId(int i)
              id=i;
         public int getId()
              return id;
         public void setDesignation(String d)
              designation=d;
         public void setName(String d)
              name=d;
         public void setSalary(int s)
              salary=s;
         public String getDesignation()
              return designation;
         public int getSalary()
              return salary;
         public String getName()
              return name;
         public void setAll()
              try
                   System.out.println("Enter name:");
                   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                   String n=br.readLine();
                   setName(n);
                   System.out.println("Enter ID:");
                   setId(Integer.parseInt(br.readLine()));
                   System.out.println("Enter Designation:");
                   n=br.readLine();
                   setDesignation(n);
                   //System.out.println("Enter Salary:");
                   //setSalary(Integer.parseInt(br.readLine()));
              catch(Exception e)
         public void getAll()
              System.out.println("Name: "+getName()+"\n ID: "+getId()+
                        "\n Designation: "+getDesignation());
         public void pay(int w)
              getAll();
              System.out.println("Name: "+name+"\nAmount to be paid : "+w);
         /*public static void main(String[] args)
              Emp e=new Emp();
              e.setAll();
              e.getAll();
    }

  • Automatically call specific method at other method invocation~ish?

    I have a class which basically acts as a wrapper around a List. It contains a List object and some methods that do something with that list.
    Now, in order to prevent exceptions, I've made a basic method that just checks if the List field is null and, if so, it will create a new ArrayList and chuck it in that field.
    Right now, I just have a call to that particular method in each other method that performs an operation on the list, like so:
    public class SomeClass<T> {
       private List<T> list;
       private void checkList() {
         if ( list == null) {
           list = new ArrayList<T>();
      public int method() {
        checkList();
        return list.doSomething();
      }Is there a way, prefferably a native Java way, to automatically have the checkList() method called before each and any method invocation? As in, whenever a method is called in the SomeClass, Java / the JVM automatically calls the checkList method?
    }

    Yop wrote:
    I have a class which basically acts as a wrapper around a List. It contains a List object and some methods that do something with that list.
    Now, in order to prevent exceptions, I've made a basic method that just checks if the List field is null and, if so, it will create a new ArrayList and chuck it in that field.
    Right now, I just have a call to that particular method in each other method that performs an operation on the list, like so:
    public class SomeClass<T> {
    private List<T> list;
    private void checkList() {
    if ( list == null) {
    list = new ArrayList<T>();
    public int method() {
    checkList();
    return list.doSomething();
    }Is there a way, prefferably a native Java way, to automatically have the checkList() method called before each and any method invocation? As in, whenever a method is called in the SomeClass, Java / the JVM automatically calls the checkList method?
    }Why not return the List<T> in the check() method? Like this:
    List<T> check() {
       if (list == null) list= new ArrayList<T>();
       return list;
    void otherMethod(T t) {
       check().add(t);
    }Instead of using variable 'list' directly, use the 'check()' method.
    kind regards,
    Jos

  • JVMTI & jni  - object tracing and method invocation

    I need to log all method invocations in the form:
    <caller object's tag, called object's tag>
    May be I 'll elaborate:
    Suppose some object of class B say b invokes a method on an object of
    class A, say instance a..
    In need the info: <object tag of b, object tag of a>
    (P.S. I donot want just the class name.. thats is available in
    stacktrace.)
    Assume tagging is done and each instance is tagged with its
    instantiation history, so two instances of same class may have have
    different tags.
    How do I do this.
    It would be great if I could get some help.

    Hi,
    are you providing in your Setup class (i am assuming is the RMI server) the two arguments constructor needed by Activatable OBject??
    it should look like this
    public Setup(ActivationID id, MarshalledObject data)
    that hopefully solves your problems
    regards
    marco

  • How to use java.lang.Class.getMethod() and java.lang.reflect.Method.invoke(

    I want to call a specified method of one class dynamically. I use the method
    "getMethod()" in package "java.lang.Class" to get method and "invoke()" in
    " java.lang.reflect.Method " to invoke method.
    The problem is as following :
    1. There are two argument in this method "getMethod(String MethodName , Class[] paremterTypes)" in package "Class". I have no idea about the second parameter " Class[] parameterTypes ".what does the argument exactly mean ?
    2. There are two argument in the method "invoke(object obj, object[] obj)" in package "Method".
    I have no idea about the second parameter "object[] obj ".what is mean ?
    I pass " null " value to it and it works.But i pass anothers ,jvm will throw exception.

    I have a generic Method Executer that has a method like
    public Object execute(String className, String methodName, Object args)
        String fullClassName = packageName + className ;
        Class delegateClass = Class.forName(fullClassName);
        BaseDelegate delegate = (BaseDelegate)delegateClass.newInstance();
        Method method = null;
        if (args == null)
            method = delegateClass.getMethod(methodName, new Class[] {});
            obj = method.invoke(delegate,new Object[] {});
        else
            method = delegateClass.getMethod(methodName, new Class[] {args.getClass()});
            obj = method.invoke(delegate, new Object[]{args});
       }This seems to have problems when I call the method from a class like:
    execute("CategoryDelegate", "getCategoryById", new Integer(4144));(I get a NoSuchMethodException)
    The method I am trying to execute in CategoryDelegate looks like:
    public Category getCategoryById(int categoryId) throws DelegateExceptionI think it has to deal with the difference in the way we handle Primitive Wrappers and Objects. Wrapper we have to use Interger.TYPE and with the rest of the Objects we have to use obj.class.
    Am I doing something wrong here? Any suggestions to make it work for primitive wrappers as well as Objects?

  • Difference between invoking a method using reflect.proxy and reflect.Method

    Could any one tell me the difference between invoking a method using reflection java.lang.reflect.Method and java.lang.reflect.Proxy
    using both the class, we can invoke a method at runtime
    1)
    Method mthd=cl.getMethod("methodName",parameterName);
    Integer output=(Integer)mthd.invoke(new RunMthdRef(),input);
    2)
    Proxy.newProxyInstance(super.getClass().getClassLoader(), new Class[] { adapter }, new SomeClass(this));
    Does anybody have any idea?

    The two idioms are fundamentally different. Using java.lang.reflect.Method is how we call a method on a class, using Proxy is how we intercept that method call. An exercise for you, to illustrate that they do not do the same thing: write a simple class with one method, then use java.lang.reflect.Method to invoke that method, and then use a Proxy to invoke that method

  • Generic method invocations with explicit type parameters

    If I interpret the JSR14 public draft spec (June 23, 2003) section 5.6 correctly the following method invocations with explicit type parameters should compile: package generics;
    public class G121 {
      void f() {
        this.<String>f2();
        <String>f2(); // compilation error
        <String>f3(); // compilation error
      <T> void f2() {
      static <T> void f3() {
    }but the class does not compile: jc -J-showversion generics\G121.javajava version "1.5.0-beta"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0-beta-b32c)
    Java HotSpot(TM) Client VM (build 1.5.0-beta-b32c, mixed mode)
    generics\G121.java:6: illegal start of expression
        <String>f2(); // compilation error
                ^
    generics\G121.java:8: illegal start of expression
        <String>f3(); // compilation error
                ^
    2 errors
    >A bug or do I miss something?

    I get this error:
    LineCount.java:104: cannot find symbol
    symbol : method <java.io.File>sort(java.util.List<java.io.File>)
    location: class java.util.Collections
    Collections.<File>sort( list );
    ^
    1 errorYou don't need the explicit type argument there, but anyway...
    If you look at the docs for Collections.sort(List<T> list) you'll see it is declared as:
    static <T extends Comparable<? super T>> void Collections.sort(List<T> list) Unfortunately, although File implements Comparable, it doesn't actually implement Comparable<File> or even Comparable<Object>, so I guess it can't satisfy the bound.
    You can get it to compile by removing the explicit type argument and casting to the raw type List, but that's not very nice.
    This seems like an oversight to me - File already has both int compareTo(Object o) and int compareTo(File pathname) so I don't see why it can't implement Comparable<File>. This isn't the only such case in the API though, so maybe I'm missing something.
    Mark

  • Can AS do reflection and method invocation?

    Hello,
    Can actionscript do reflection, instantiation, and subsequent
    invocation of a method, as in java ?
    this.incidentVO=incident;
    Class c = IncidentRules.class;
    Class[] parameterTypes = null;
    Method methodName;
    methodName =
    c.getMethod("validate"+commandName,parameterTypes);
    methodName.setAccessible(true);
    methodName.invoke(this,null);

    Unlike Java, AS is dynamic:
    var ClassReference:Class =
    getDefinitionByName(“flash.display.Sprite”) as Class;
    var instance:Object = new ClassReference();
    instance.graphics.beginFill(bgColor);
    instance.graphics.drawRect(0, 0, size, size);
    instance.graphics.endFill();
    addChild(DisplayObject(instance));
    Note the type of variable called 'instance'. It's Object.
    Still, it's calling method(s) of the underlying object without a
    compile time warning.
    Also, unlike Java AS has construct like object["property"]
    which would either return the reference to the property of null if
    object doesn't have given property.
    Also in AS you have class called Function that represents a
    function.
    Now, the real fun begins! Although AS doesn't have OO
    reflection like Java, but we can combine above constructs to do the
    job.
    here is you basic class with two functions:
    public class XV
    public function hello1(s:String) : void {
    trace('message from XV.hello1: ' + s);
    public function hello2(s:String) : void {
    trace('message from XV.hello2: ' + s);
    now you want to call hello1 and hello2.
    Now, if you run code like:
    1 var xv:XV = new XV();
    2 var m:String = "hello";
    3 var f:Function = xv[m + "1"];
    4 f.call(this, 'Hello World!');
    note line 3 above. You're looking for a property called
    hello1 and you *know* it's a function so you get a reference of it.
    On line 4 so simply call it with only argument of type String!
    Hope this helps!
    ATTA

  • Using Reflection - Method.invoke()

    Hi all,
    Facing a problem in using the Reflection API. Can anyone tell me how to use the invoke, which is available with Method. Problem statement. - I want to create a method. And then invoke that method using method1. invoke. But this can take only the following arguments - (Object, Object [ ] ). I cant figure out why I need to pass on an object ? and an array of objects ?

    If you read the docs for Method.invoke, you'll see that the first argument is the object on which you wish to invoke the method, and the second argument is the parameters (with primitives wrapped appropriately).
    foo.bar("abc", 123);
    // becomes
    meth.invoke(foo, new Object[] {"abc", new Integer(123) }); (if I haven't screwed up the syntax of the array initialization)
    http://java.sun.com/docs/books/tutorial/reflect/

Maybe you are looking for

  • Background images with spry "horizontal menu"

    hi again I am trying to work with the spry: "horizontal menu" I want to put some background images into the menu bar not into the submenu and that is the problem: the background images appears overall what can I do ? <head> <meta http-equiv="Content-

  • Safari needs to click submit button twice when file uploading

    Hi all, I'm using Safari 4.0.5 and developing the html (no AJAX, but plain PHP posting) form with the file uploading on my local environment. I tested it fast and thick several times, then suddenly Safari stopped to upload the jpeg file, indicating l

  • Error Differance is too large for Customer clearning

    Hi, When I am trying to clear the customer f-32 i am getting the error as "(F5 263) The difference is too large for clearing". Excise invoice is created in USD . when i clear the payment in indian currency the erors occurs. Request you to please help

  • Binary Tree Help

    I have a project where I need to build a binary tree with random floats and count the comparisons made. The problem I'm having is I'm not sure where to place the comaprison count in my code. Here's where I have it: public void insert(float idata)    

  • Subsequent implentation of EWT (Challan and Certificate)

    Hello, We are on SAP ECC6 for nearly 2 years now. EWT functionality has been implemented and TDS is getting deducted as per the provisions of the Indian Income Tax Act but Bank Challans, TDS Certificate and Quarterly Return are outside SAP. There is