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

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

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

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

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

  • Java Reflection API problem... Please HELP!

    Hi,
    I'm writing a Client-Server program set where the Server class receives a Java file, along with some parameters, from the Client class/computer.
    The Server class then invokes a certain method from the Java file it received (depending on the parameters received).
    My Server program keeps giving me a ClassNotFoundException, and I'm going crazy.. I've been trying to fix it for a long time now... but with no avail.
    Here's the Server program.. but I doubt you need to read it all. Please just scroll down to "// The line below is what give me problems:".
    package remoterun;
    import java.net.*;
    import java.io.*;
    import java.lang.reflect.*;
    * <p>Copyright: Copyright ms2000 (c) 2005</p>
    public class Server2 {
        public static void main(String args[]) throws Exception {
            int numParameters;
            int port = 6789;
            boolean isThere = false;
            String className, methodName;
            Object[] parameters;
            ServerSocket welcomeSocket = new ServerSocket(port);
            for (; ; ) {
                 * Create a new socket, called connectionSocket, when some client knocks
                 * on welcomeSocket. This socket has the same port number. TCP then
                 * establishes a direct virtual pipe between the client socket and
                 * connectionSocket at the server so the client and server can send bytes
                 * to each other over it.
                Socket connectionSocket = welcomeSocket.accept();
                // Get number of parameters
                DataInputStream in = new DataInputStream(new BufferedInputStream(
                        connectionSocket.getInputStream()));
                numParameters = in.readInt();
    // Get the parameters for the method to be invoked.
                parameters = new Object[numParameters];
                ObjectInputStream objStream = new ObjectInputStream(
                        connectionSocket.getInputStream());
                for (int i = 0; i < numParameters; i++) {
                    parameters[i] = objStream.readObject();
                // read the class
                File program = (File) objStream.readObject();
                System.err.println(program); // It prints the program name correctly, e.g. Class2.java
    // Receiving some String parameters...
                            BufferedReader inFromClient = new BufferedReader(new
                        InputStreamReader(connectionSocket.getInputStream()));
                className = inFromClient.readLine();
                methodName = inFromClient.readLine();
                // The line below is what give me problems:
                Class classDefinition = Class.forName("remoterun." + className + ".java");
                Object object = classDefinition.newInstance();
                Method[] theMethods = classDefinition.getMethods();
                for (int i = 0; (i < theMethods.length) && (!isThere); i++) {
                    if (theMethods.getName().equals(methodName)) {
    isThere = true;
    theMethods[i].invoke(object, parameters);
    The Client code just sends the stuff to the Server, and it works fine. The code is below if it may help:
    package remoterun;
    import java.net.*;
    import java.io.*;
    public class Client2 {
        public static void main(String[] args) throws Exception {
            int result;
            int port = 6789;
            int num1 = 5;
            int num2 = 6;
            int numParameters = 3;
            String hostIP = "127.0.0.1";
            String className = "Class2";
            String methodName = "add";
            Object[] parameters;
            Socket clientSocket = new Socket(InetAddress.getByName(hostIP),
                                             port);
            // Send numParameters, className, methodName
            DataOutputStream out = new DataOutputStream(new BufferedOutputStream(
                    clientSocket.getOutputStream()));
            out.writeInt(numParameters);
            out.flush();
            Integer num3 = new Integer(num1);
            Integer num4 = new Integer(num2);
            parameters = new Object[] {num3, num4, InetAddress.getLocalHost()};
            File program = new File((className + ".java"));
            ObjectOutputStream output = new ObjectOutputStream(clientSocket.
                    getOutputStream());
            for (int i = 0; i < numParameters; i++) {
                output.writeObject(parameters);
    output.writeObject(program);
    output.flush();
    DataOutputStream outToServer = new DataOutputStream(clientSocket.
    getOutputStream());
    outToServer.writeBytes(className + '\n');
    outToServer.writeBytes(methodName + '\n');
    outToServer.flush();
    clientSocket.close();
    The error I get from the Server class is:
    java.lang.ClassNotFoundException: remoterun.Class2.java
    at java.net.URLClassLoader$1.run(URLClassLoader.java:199)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:141)
    at remoterun.Server2.main(Server2.java:94)
    Exception in thread "main"
    (I also get a dialog box saying sthg like, "A fatal exception occured.. will exit now".)
    It's really odd, becuase there were rare times when it works although I don't change the program...
    I tried changing the problem line to stuff like:
                Class classDefinition = Class.forName(className + ".java");or
       Class classDefinition = Class.forName(className);but with no use. Same error. Can someone please pinpoint the problem?
    I'm sure the program does get to the Server, because it can print out the file name.
    PS: Sometimes it works when I use the same PC as the client/server, sometimes it doesn't.... Help :-(
    I'd appreciate some assistance in this.
    Thank you.

    What's this dot-java stuff? Are you sending a source file? If so, that isn't going to work. You need to compile the file and send the dot-class file.
    I'll try that. However, can I make the Client program complie the .java file? For example. something like Class2.compile()? Is this feature available, or do I have to open Class2.java and compile it from there?
    And in the server you need to either store that somewhere in the server's classpath....
    Isn't it automatically stored there? If not, how do I make it stored in the same file as the Server source file (I assume that's what you mean by classpath)?
    Thanks for your help... !!!

  • Java Reflection Help

    Guys I have a string
    vtEvents.byteArrayEventInterfaceHelper.getMetaObject().findDef("byteArrayEvent")
    How do i create a reflection class for this and execute the above statement.

    What's this dot-java stuff? Are you sending a source file? If so, that isn't going to work. You need to compile the file and send the dot-class file.
    I'll try that. However, can I make the Client program complie the .java file? For example. something like Class2.compile()? Is this feature available, or do I have to open Class2.java and compile it from there?
    And in the server you need to either store that somewhere in the server's classpath....
    Isn't it automatically stored there? If not, how do I make it stored in the same file as the Server source file (I assume that's what you mean by classpath)?
    Thanks for your help... !!!

  • Java Reflection Exception

    When reading a date from the database and using reflection to set a java.sql.Date field in my class I am getting the following error:
    java.lang.IllegalArgumentException
              at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63)
              at java.lang.reflect.Field.set(Field.java:519)However the value does appear to be getting set.
    Even more strangely if I change the field that I am trying to set to a java.util.Date type then it works fine, but then I can't use the PreparedStatement.setObject() method to set the date for an update/insert.
    So I can't win, I can either update or read but not both.
    Any ideas?

    >
    Any ideas?The javadocs for Field.set(Object obj,Object value) provides a very specific list of why an IllegalArgumentException might be thrown.
    My guess is that you have a access modifier problem. But since you didn't provide code I can't say for certain.

  • Java Reflection: Trying to access a constrcutor with an array argument.

    Having some reflection problem... upon reflection maybe I shouldn't use reflection... :-)
    The classes I use to test this are defined as follows:
    class MyTestClass{
      public long[] _array;
      public MyTestClass(long[] array)
        _array = array;
    class MyTestClass2{
      public int[] _array;
      public MyTestClass2(int[] array)
        _array = array;
    class MyTestClass3{
      public String[] _array;
      public MyTestClass3(String[] array)
        _array = array;
    class MyTestClass4{
      public Long[] _array;
      public MyTestClass(Long[] array)
        _array = array;
    }and this is how I try to access it:
      // Only classes that have a constrcutor with a single
      // param which is an array can be used with this method.
      // The class also has to define a public field called "_array"
      // which is of the ssame type as the parameter of the
      // constructor
      public Object getNewInstanceOf(String className)
        // getValues uses reflection to instanciate an array of objects of
        // certain types which are not known to start with, i.e getValues
        // can return Long[] or Integer[] or String[]
        Object[] values = getValues();
        Class myClass = Class.forName(className);
        myClass..getField("_array");
        Class paraClass = field.getType();
         Constructor constructor = myClass
                    .getConstructor(new Class[]{paraClass});
        // the problem occurs here, I think I would have to cast "values" to the
        // proper array type, but don't know how to do this using reflection.
        Object  myInstance = constructor.newInstance(new Object[]{values});
       return myInstance;
      private Object[] getValues()
        // use reflection to create the array
      }and this is the error I get
    java.lang.IllegalArgumentException: argument type mismatch

    we can be much helpfull if we do not know which line excatly throws exception
    normaly stack trace shows the line number so can you re-post your code highlitine the line which throws given exception

Maybe you are looking for