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

Similar Messages

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

  • Can Java reflect not only .Class file

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

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

  • Java Access Helper Jar file problem

    I just downloaded Java Access Helper zip file, and unzipped, and run the following command in UNIX
    % java -jar jaccesshelper.jar -install
    I get the following error message, and the installation stopped.
    Exception in thread "main" java.lang.NumberFormatException: Empty version string
    at java.lang.Package.isCompatibleWith(Package.java:206)
    at jaccesshelper.main.JAccessHelperApp.checkJavaVersion(JAccessHelperApp.java:1156)
    at jaccesshelper.main.JAccessHelperApp.instanceMain(JAccessHelperApp.java:159)
    at JAccessHelper.main(JAccessHelper.java:39)
    If I try to run the jar file, I get the same error message.
    Does anyone know how I can fix this?
    Thanks

    Cross-posted, to waste yours and my time...
    http://forum.java.sun.com/thread.jsp?thread=552805&forum=54&message=2704318

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

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

  • Java Access Helper problem

    I just downloaded Java Access Helper zip file, and unzipped, and run the following command in UNIX
    % java -jar jaccesshelper.jar -install
    I get the following error message, and the installation stopped.
    Exception in thread "main" java.lang.NumberFormatException: Empty version string
    at java.lang.Package.isCompatibleWith(Package.java:206)
    at jaccesshelper.main.JAccessHelperApp.checkJavaVersion(JAccessHelperApp.java:1156)
    at jaccesshelper.main.JAccessHelperApp.instanceMain(JAccessHelperApp.java:159)
    at JAccessHelper.main(JAccessHelper.java:39)
    If I try to run the jar file, I get the same error message.
    Does anyone know how I can fix this?
    Thanks

    sorry ab the multiple post, it was urgent for me to
    know the answer.
    I've JDK 1.4.2 and JAccessHelper should work with 1.3
    or later
    Can there be some kind of path problems?No, I doubt it. It's just some internal app failure - looks like it's trying to determine the running Java version, and is not doing a good job at it. But the failure has nothing per se to Java, it's that specific app - what are we supposed to know about that app though?

  • New to java(need help on access specifier)

    hi! i am new to java.plzzzzz help me i have to make a project on access specifier's i know all theroy.but
    i am unable to understand how i can define all specifiers practicly.i mean in a program.
    thanks.plzzzzzzzz help me

    the most common project i can think of is a payroll system..
    you can have real implementation of all the access specifiers
    good luck

  • Pascal to Java Please help me!

    I am truobled in creating a validation method for the user loging in....
    As I am perfect at Pascal can anyone translate the following pascla code to Java Please help me with this.
    PROGRAM USERLOGIN;
    TYPE
      USER_TYPE = RECORD
        USERNAME : STRING[15];
        PASSWORD : STRING[15];
    END;
        USFILE = FILE OF USER_TYPE;
    VAR
       USER: USER_TYPE;
       CKUSER: USER_TYPE;
       RECFILE : USFILE;
       I,J     : INTEGER;
    BEGIN
    WRITE('ENTER USERNAME:');READLN(CKUSER.USERNAME);
    WRITE('ENTER PASSWORD:');READLN(CKUSER.PASSWORD);
    FILESPEC :='USERFILE.USR';
    ASSIGN(RECFILE, FILESPEC);
    RESET(RECFILE);
      WHILE NOT EOF(RECFILE) DO
       BEGIN
         READ(RECFILE, USER);
         IF CKUSER.USERNAME = USER.USERNAME AND CKUSER.PASSWORD = USER.PASSWORD THEN
              LOGIN
        ELSE
              WRITE('USER NOT FOUND');
       END;
    END.Thank you

    Don't bother:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=539277

  • How I can enable Java ssv helper plugin silently for win7 users with IE9

    here is what happens:
    when I deploy java 7.21 on win7 users, after deployment when users try to Open their IE they get a login screen and apparently it is related to Java ssv helper plugin. it is trying to enable it and needs admin account/password. I am trying to deploy this to about 3000 computers and I dont want all of them start calling helpdesk for this.
    your help is appreciated.

    The following article describes how to create a shared preference file. You can either create preferences that individual users can override, or create locked preferences that individual users cannot override.
    http://kb.mozillazine.org/Lock_Prefs
    (Note: I don't have any personal experience with these files, but another volunteer might post some additional tips and tricks.)

Maybe you are looking for