Using reflection on passed classes

Hello,
I have been trying to write a common function to return the variables and values of a class passed into it. The function uses reflection to iterate through the Fields and returns a string of the variables and values. Is it anything to do with scope, as the same code works when I paste the method into the class I am looking at (See below)?
I have pasted the code fragments below.
Thanks
stuart
* Returns XML fragment of name value pairs of member/value
* @param iClass the class under inspection
* @return XML fragment of name value pairs of member/value
public static String inspectMemberVariables(Class iClass)
String oStr = new String();
try
Class c = iClass.getClass();
Field[] f = c.getFields();
System.out.println(f.length);
for (int i=0; i < f.length; i++)
// identify the field
Field fld = c.getField( f.getName());
//get the field name and grab the field value from the class
oStr += f.getName()
+ "=\""
+ fld.get(c)
+ "\" ";
} // for (int i=0; i < f.length; i++)
oStr = "classname=\""
+ c.getName()
+ "\" "
+ oStr;
} //end of try
catch (NoSuchFieldException e)
System.out.println(e);
catch (SecurityException e)
System.out.println(e);
catch (IllegalAccessException e)
System.out.println(e);
} //end of catch
return oStr;
} // end ofinspectMemberVariables
Where the code is called:
public class ReflectionTest extends PPSpposEBCore
public String strg;
public ReflectionTest()
String str2 = new String ();
str2 = ClassProperties.inspectMemberVariables(this.getClass());
System.out.println(str2);
public static void main(String[] args)
String str = new String ();
try
ReflectionTest rt = new ReflectionTest();
// set dummy values to test
rt.mPossessionId = 12;
rt.mBusinessPossRef = "look it works";
rt.mCreatedTs = new Date();
//ClassProperties cp = new ClassProperties();
//str2 = ClassProperties.inspectMemberVariables(rt.getClass());
Class c = rt.getClass() ;
Field[] f = c.getFields();
System.out.println(f.length);
for (int i=0; i < f.length; i++)
// identify the field
Field fld = c.getField( f.getName());
//grab the field name and field value from the class
str += f.getName()
+ "=\""
+ fld.get(rt)
+ "\" ";
} // for (int i=0; i < f.length; i++)
str = "classname=\""
+ c.getName()
+ "\" "
+ str;
System.out.println(str);
} //try
catch (NoSuchFieldException e)
System.out.println(e);
catch (SecurityException e)
System.out.println(e);
catch (IllegalAccessException e)
System.out.println(e);

sorry it doesn't work, interface cannot have method body, i didn't know it. You couldn't access to private and protected datas with an exterior method. You can make a package with classes you want to inspect and a class who inspect. The classes of a package can access to protected datas.

Similar Messages

  • Class A is Loading Class B Using Reflection

    Hi,
    I am facing the below problem.
    Class A is loading Class B By Using Reflection package.
    Class B is one jar (Eg: B.jar) ,Class A is one Jar (Eg: A.jar)
    Class B internally using Class A variables and methods. When ever loading the class B from Class A it is
    giving the exception is NoClassDefFoundError of Class A.
    We are loading the Class B from Class A only, Why Class A reference is not available in Class B
    Please help me on this
    Thanks
    T. Shankar Reddy

    ShankarReddyT wrote:
    Hi,
    I am facing the below problem.
    Class A is loading Class B By Using Reflection package.
    Class B is one jar (Eg: B.jar) ,Class A is one Jar (Eg: A.jar)
    Class B internally using Class A variables and methods. Myself I don't consider circular references a great idea.
    Presumably you are not using reflection solely because it is circular.
    When ever loading the class B from Class A it is
    giving the exception is NoClassDefFoundError of Class A.
    We are loading the Class B from Class A only, Why Class A reference is not available in Class B
    Several possibilities.
    1. Because you are attempting to load B in the static block of A. In that case the class A has not yet been loaded. And the VM will not try to reload A once it is in the process of loading. Which is pretty smart of the VM.
    2. Because there is a custom class loader involved.
    You might want to post the stack trace of the exception.

  • XML document creation using reflection

    Hi all,
    I'm tyring to write a class which creates an XML document from objects passed in. For example, you call the add(Object) method and it takes your object, uses reflection, then outputs XML like this...
    <fieldName>fieldValue<fieldName>
    The only problem is that after looking through this forum I am a little concerned about the performance of my proposed solution (using reflection).
    The class will be used in a batch process which processes millions of objects (to generate a whopping XML file that'll be sent on for further processing by a third party).
    Is there a better way to do this than by using reflection?
    This class is going to be used by multiple batch processes hence there will be lots of different object types passed (they'll also be new ones in the future that we don't even know about yet) hence my reflection choice.
    Thanks,
    Chris

    The only problem is that after looking through this
    forum I am a little concerned about the performance of
    my proposed solution (using reflection).The only way that you'll know for sure is if you try it out. Write the code, test it, then run it in a profiler to find out where the performance problems (if any) are.
    Is there a better way to do this than by using
    reflection?Probably not, if you want to pass any arbitrary object to it.
    One possible alternative is to have "XML aware" objects: define an interface WritesXML, that defines a method toXML(). You then check to see whether the given object implements this interface, and if it does you simply call the method, otherwise you use reflection.
    Another alternative, assuming that your objects follow the Bean pattern, is to create "XML-ifiers" on the fly, similar to the way an app-server handles JSPs. First time you see an object you create a class that will write it to XML, then compile this class and invoke it for all subsequent objects. This will require that you have a JDK installed on the runtime machine, that the objects follow the Bean pattern, and that the number of instances of a given class are very high.
    This class is going to be used by multiple batch
    processes hence there will be lots of different object
    types passed (they'll also be new ones in the future
    that we don't even know about yet) hence my reflection
    choice.Sounds like a good reason to use reflection.

  • Creating objects using reflection

    Hi,
    I need to construct a new instance using reflection and passing parameters. If the parameters are of primitive type ex. int, how can I pass them in the Class[] type of object

    Integer.TYPE, etc. are Class objects that represent the types of the primitives.

  • Reflection - reading a .class file

    I want to read in a .class file, and be able to use reflection to get a list of that class's methods. I'm using a JFileChooser to find the file, I just need to know how to use the output from the JFileChooser (a path to the file) to load the file into the program, and use reflection methods to create an appropriate Class object.

    kajbj wrote:
    fredley_m wrote:
    kajbj wrote:
    fredley_m wrote:
    I don't think I'm making myself clear. I can read in a file, I don't know how to use reflection on a .class file. I need to know how to complete the following line of code:
    Class reflectedClass =reflectedClass should then contain a copy of the class from the .class file.You load a class using Class.forName(..)This does not work.
    JFileChooser fc = new JFileChooser();
    int returnVal = fc.showOpenDialog(main_panel);
         if(returnVal == 0)
              String fileName = fc.getSelectedFile().getName();
              fileName = fileName.substring(0,fileName.lastIndexOf('.')); //also doesn't work without this line
              Class c = Class.forName(fileName);
    ...I get a ClassNotFoundException when I try to open MyClass.classYou need to know about how class loaders work, and use one. Read the javadoc:
    [http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html]
    The NetworkClassLoader sample is pretty close to what you want.Thanks, the URLClassLoader is perfect, however my code:
    String fileName = fc.getSelectedFile().getName();
    fileName = fileName.substring(0,fileName.lastIndexOf('.'));
    URL[] urls = {new URL(filePath)};
    URLClassLoader cl = new URLClassLoader(urls);
    Class c = cl.findClass(fileName);does not compile: "findClass has protected access"

  • How can i get all java class names from a package using reflection?

    hi,
    can i get all classes name from a package using reflection or any other way?
    If possible plz give the code with example.

    You can't, because the package doesn't have to be on the local machine. It could be ANYWHERE.
    For example, via a URLClassLoader (ie from the internet) I could load a class called:
    com.paperstack.NobodyExpectsTheSpanishInquisitionI haven't written it yet. But I might tomorrow. How are you going to determine if that class is in the package?
    This subject comes up a lot. If you want to do something a bit like what you're asking for (but not quite) there are plenty of threads on the subject. Use google and/or the forum search facility to find them.
    But the answer to your question, as you asked it, is "you can't do that".

  • Using Reflection can we find out details of inner classes in a class

    Hello All,
    Thanx in advance.
    I intend to figure out the name of the inner class and methods declared inside it. How can this be done using reflection API's.
    I need the above information to make an automated java doc creation tool for the project I am working in.
    Thanx again...
    VIkas

    Thanx silkm,
    Actually suggestion # 1 I have already tried. I used
    getClasses() method which returned me a Class[] of
    length = 0. i dunno Why?Because you are not using the reflection API correctly. If you read the javadocs you would know that it is structured so that all getXXX() methods return all XXX things that are public and are either declared by the target class or possibly inherited from superclasses.
    As contrasted to that, getDeclaredXXX() methods can return all XXX things (including private) but only declared by the target class (not inherited).
    You got an empty result back in your case most likely because all your nested/inner classes were non-public. Use getDeclaredClasses() instead.
    As to suggestion # 2, the exercise I am doing is a
    step before using the java doc tool. One has to insert
    a javadoc comment before the method begins in order to
    create a java doc. So thats it.This is independent of the reflection API but you might consider using the doclet API for this.

  • How to access private method of an inner class using reflection.

    Can somebody tell me that how can i access private method of an inner class using reflection.
    There is a scenario like
    class A
    class B
    private fun() {
    now i want to use method fun() of an inner class inside third class i.e "class c".
    Can i use reflection in someway to access this private method fun() in class c.

    I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
    Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
    So here's what it looks like:
            //list of inner classes, if any
            Class[] classlist = A.class.getDeclaredClasses();
            A outer = new A();
            try {
                for (int i =0; i < classlist.length; i++){
                    if (! classlist.getSimpleName().equals("B")){
    //skip other classes
    continue;
    //this is what I mention above.
    Constructor constr = classlist[i].getDeclaredConstructor(A.class);
    constr.setAccessible(true);
    Object inner = constr.newInstance(outer);
    Method meth = classlist[i].getDeclaredMethod("testMethod");
    meth.setAccessible(true);
    //the actual method call
    meth.invoke(inner);
    } catch (Exception e) {
    throw new RuntimeException(e);
    Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to use reflection to get base classes protected field

    I have one base Base classes which have protected fields and public get method to get the field.
    class Base
    protected int proField;
    public int getProField(){return proField;}
    Class Derive extends base class Base
    class Derive extends Base implements OtherInterface
    public void funtion(){};
    Now I have an instance of Derive, how can I use reflection to get the protected field inherited from Base. It seems Java Reflection only give runtime accessibility to public field and decleared field, protected-inherited field is excluded.
    Thanks
    Lei

    as the last poster said, traverse up the class hierarchy.
    ex:
    private void doSumfinToField(String fieldName throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
    Class clazz = getClass();
    Field field = findFieldInClass(clazz, fieldName);
    //field.doSumfin;
    private Field findFieldInClass(Class clazz, String fieldName) throws NoSuchFieldException {
    try { // to find the field in this class    
    return clazz.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
    // if we don't have a superclass, continue
    if (clazz.getSuperclass().equals(Object.class)) {
    throw e;
    // check in the superclass
    return findFieldInClass(clazz.getSuperclass(), fieldName);
    }

  • Instantiation an inner class using reflection

    I want to instantiate an inner class using the Class.newInstance() method called within the Outer class constructor:
    public Outer
    public Outer()
    Inner.class.newInstance();
    private Class Inner { }
    When I try it, however, I get an InstantiationException.
    Is there some way to do this?
    Thanks for the help.
    Scott

    Here is a consolidation of what everyone posted and it does appear to work. In one of your post you used the getDeclaredConstructors() method and said it was less than ideal; I am not sure what you meant but I suspect it was the hard coded array reference. Anyhow I used the getDeclaredConstructor() method which appears to get non-public constructors also and is basically the same as using the getConstructor() method.
    import java.lang.reflect.*;
    public class Test35 {
        static public void main(String[] args) {
            Test35 t35 = new Test35();
            t35.testIt();
        private class Inner {
            public String toString() {
                return "Hear I am";
        public void testIt() {
            try {
                Constructor con = Inner.class.getDeclaredConstructor(new Class[] {Test35.class});
                Inner in = (Inner)con.newInstance(new Object[] {this});
                System.out.println(in);
            } catch (Exception e) {
                e.printStackTrace();

  • Instantiating member classes using reflection

    I have checked through this forum but if the answer to this question is here I missed it.
    I am trying to find out how to invoke the appropriate instantiation / constructor call to create an instance of a member class.
    The following works finepublic class Succeeds {
      public abstract static class AbstractMember {
      Succeeds(final AbstractMember am) {
      public static void main(final String[] args) {
        Succeeds a = new Succeeds (new Succeeds.AbstractMember () {
    }However I want to make the AbstractMember a real member class not a nested inner class and I want to instantiate the concrete subclass of AbstractMember in the constructor of Succeeds rather than outside the class. I tried the following:public class Fails {
      public abstract class AbstractMember {
        public class ConcreteMember extends AbstractMember {
      Fails(final Class<? extends AbstractMember> c)
        throws InstantiationException, IllegalAccessException {
        AbstractMember am = c.newInstance() ;
      public static void main(final String[] args)
        throws InstantiationException, IllegalAccessException {
        Fails a = new Fails (Fails.AbstractMember.ConcreteMember.class) ;
    }(Please forgive the appling treatment of exceptions, I wanted to make a small example). This compiles fine but fails at runtime with an InstantiationException I assume because the nullary constructor doesn't exist for a member class because of the need to make the connection to the containing object.
    So the question is is there a bit of reflection that allows me to achieve what I want?
    I cannot be the first person to try doing this. I am hoping it is doable otherwise I am going to have to make the design a bit yukky.
    Thanks.

    import java.lang.reflect.*;
    public class Fixed
        public abstract class AbstractMember
        public class ConcreteMember extends AbstractMember
        <T extends AbstractMember> Fixed(final Class<T> c) throws Exception
            Constructor<T> ctor = c.getConstructor(new Class[]{getClass()});
            AbstractMember am = ctor.newInstance(new Object[]{this});
        public static void main(final String[] args) throws Exception
            new Fixed(ConcreteMember.class);
    }My exception handling is even more lax than yours. Why isn't there a class ReflectionException? I moved ConcreteMember out of AbstractMember to keep things simple. It's not entirely necessary, but I didn't want to construct an AbstractMember first.

  • A Universal Comparator using reflections

    Folks,
    <edit purpose="bump" secondaryPurpose="explain stuff a bit better">
    Sorry I didn't explain what this thing is... and zero bites in the veiw of several active silver backs means, I presume, that I did something magorly wrong... so...
    This class class calls the compare method passing the result of named "getter" method on the two objects to compare. So what? Well... Ummm... It means you can sort by any field of any List (or PriorityQueue, or what-have-you) without having to pre-write a Comparator.... Which is good.
    </edit>
    I was inspired by a blog entry by ?was it warnerja? which was referenced in a thread which was linked from an off-topic post in a thread I read last ?Thursday? night... and to cut a long storry short... I can't find the blog entry again :(
    My implementation is based on [this one by Lone Deranger|http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=3308&lngWId=2] ... which has a couple of problems
    1. infinite recursion in the equals method == OutOfStackSpaceException
    2. It gets the method defintion every time you call compare == sloooooooooooowwwwwwwwwww.
    This version
    * is a bit faster
    * verifies as much as possible in constructor.
    * uses generics to verify (as far as possible) the runtime "compared Class" type.
    But I'm pretty sure someone who really knows there generics could improve upon the implementation (or quit possibly the fundamental design). Specifically I'm not in love passing the Class of the compared objects as well as define the generic type. There's GOT to be a better way... I'm just to inexpert/stupid to recognise it... I've probably been staring straight at it for the last two hours.
    So.... This thing works... but any suggestions and/or constructive criticism would be welcome ;-) Thanx.
    UniversalReflectiveComparator.java
    package forums;
    import java.util.Comparator;
    import java.lang.reflect.Method;
    import java.lang.reflect.Type;
    public class UniversalReflectiveComparator<T> implements Comparator<T>
      public static String DEFAULT_METHOD_NAME = "toString";
      public static final int ASCENDING = 1;
      public static final int DESCENDING = -1;
      public static int DEFAULT_ORDER = ASCENDING;
      private static final java.lang.Object[] NO_ARGS = null;
      private final String methodName;
      private final Method getterMethod;
      private final int order;
      public UniversalReflectiveComparator(Class classToCompare)
        throws NoSuchMethodException
        this(classToCompare, DEFAULT_METHOD_NAME, DEFAULT_ORDER);
      public UniversalReflectiveComparator(Class classToCompare, String methodName)
        throws NoSuchMethodException
        this(classToCompare, methodName, DEFAULT_ORDER);
      public UniversalReflectiveComparator(Class classToCompare, int order)
        throws NoSuchMethodException
        this(classToCompare, DEFAULT_METHOD_NAME, order);
      @SuppressWarnings("unchecked")
      public UniversalReflectiveComparator(Class classToCompare, String methodName, int order)
        throws NoSuchMethodException
        getterMethod = classToCompare.getMethod(methodName, (java.lang.Class<?>[])null);
        Class returnType = getterMethod.getReturnType();
        if ("void".equals(returnType.getName())) {
          throw new IllegalArgumentException("Cannot compare on the '"+methodName+"' method"
          + " because its return type is void (ie: it does not return a value to compare).");
        if ( !doesImplement(returnType, Comparable.class.getCanonicalName()) ) {
          throw new IllegalArgumentException("Cannot compare on the '"+methodName+"' method"
          + " because its return type '"+returnType.getName()+"' does not implement Comparable.");
        this.methodName = methodName;
        this.order = order;
      @Override
      @SuppressWarnings("unchecked")
      public int compare(T o1, T o2) {
        try {
          Comparable o1attribute = (Comparable) getterMethod.invoke(o1, NO_ARGS);
          Comparable o2attribute = (Comparable) getterMethod.invoke(o2, NO_ARGS);
          return o1attribute.compareTo(o2attribute) * order;
        } catch (Exception e) {
          throw new IllegalStateException("Failed to compare "+clazz(o1)+ " to "+clazz(o2), e);
       * Returns the type and string value of the given object.
       * eg: java.lang.String 'Hello World!'
      private static String clazz(Object object) {
        return object.getClass().getCanonicalName()+" '"+String.valueOf(object)+"'";
       * Returns: Does the given clazz implement the given interfaceName
       * @param clazz the Class to be examined.
       * @param canonicalInterfaceName the full name (with or without generics)
       *  of the interface sought: path.to.Interface[<path.to.GenericType>]
      private static boolean doesImplement(Class clazz, String canonicalInterfaceName) {
        for ( Type intrface : clazz.getGenericInterfaces() ) {
          if ( intrface.toString().startsWith(canonicalInterfaceName) ) {
            return true;
        return false;
    UniversalComparatorTest.java
    package forums;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    // A simple "Bean" class for testing only.
    // Does NOT implement comparable!
    class Word {
      private final String word;
      public Word(String word) { this.word=word; }
      public String getWord() {  return this.word; }
      public void noop() { }
      public String toString() { return this.word;  }
      public Word notComparable() { return new Word("notComparable"); }
    class UniversalComparatorTest
      @SuppressWarnings("unchecked")
      public static void main(String[] args) {
        try {
          List<Word> words = readWords("WordFinder.txt");
          System.err.println("---------------------------------------------------");
          // SUCCESS CASES
                           //short for new UniversalReflectiveComparator<Word>(Word.class,"toString",ASCENDING);
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class));
            System.out.println(words);
          } catch (Exception e) {e.printStackTrace();}
          System.err.println("---------------------------------------------------");
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class, "getWord", UniversalReflectiveComparator.DESCENDING));
          } catch (Exception e) {e.printStackTrace();}
          System.out.println(words);
          System.err.println("---------------------------------------------------");
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class, UniversalReflectiveComparator.DESCENDING));
          } catch (Exception e) {e.printStackTrace();}
          System.out.println(words);
          System.err.println("---------------------------------------------------");
          // FAIL CASES
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class, "nonExistantMethodName"));
          } catch (Exception e) {e.printStackTrace();}
          System.err.println("---------------------------------------------------");
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class, "noop"));
          } catch (Exception e) {e.printStackTrace();}
          System.err.println("---------------------------------------------------");
          try {
            Collections.sort(words, new UniversalReflectiveComparator<Word>(Word.class, "notComparable"));
          } catch (Exception e) {e.printStackTrace();}
          System.err.println("---------------------------------------------------");
        } catch (Exception e) {
          e.printStackTrace();
       * reads each line of the given file into a List of strings.
       * @param String filename - the name of the file to read
       * @return an List handle ArrayList of strings containing file contents.
      public static List<Word> readWords(String filename) throws FileNotFoundException, IOException {
        List<Word> results = new ArrayList<Word>();
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(filename));
          String line = null;
          while ( (line=reader.readLine()) != null ) {
            results.add(new Word(line));
        } finally {
          if(reader!=null)reader.close();
        return results;
    }Cheers all. Keith.
    PS: If you happen to know that blog entry... could you post a link... please.
    Edited by: corlettk on 2/11/2008 15:52 - Ooops!
    Edited by: corlettk on 2/11/2008 18:20 - You Snobs!
    Edited by: corlettk on 2/11/2008 19:00 - Dodgems bump!

    Here's the latest installment...
    This thing writes, compiles and instantiates and caches the requested implementation of Comparator<?> on-the-fly with the system default javax.tools.JavaCompiler
    Some Notes:
    * Gee, it's just sooooo easy to invoke the compiler.
    * Compilation errors are printed to stdout.
    * It takes too long to compile... aprox nine-tenths of a second (0.95 +/- 0.04) for a really simple little class.
    * I like the cache... subsequent calls for the same comparator are instant ;-)
    * Possible enhancement: oninit: load the cache with .class's from the specified package (a seperate comparators package), so you only have to create each comparator once per release (ie: like JSP's)
    * It throws too many distinct exception types... I think it would be better if it threw only one ComparatorGenerationException (but I'm too lazy to fix it now).
    * I don't like the "staticness" anymore, especially with a cache involved. Maybe a ComparatorFactoryConfig extends Properties would be the best way to configure the factory? Or maybe a ComparatorSpec class should be passed to the createComparator method... to eliminate all that cumbersome overloading to just to provide defaults. Hmmm.
    * The order switch means you can sort both ways using the one generated
    * A simillar "nulls first or last" switch would be a good enhancement.
    * Camickr's solution also features a case[in]senstive switch... feel free to add it ;-)
    * It's still not a scratch on Mr Kirkman's ASM solution (which is aprox 10 times as fast), but it'll definately give the "pure reflection" solution a run for it's money.
    * I can imagine a common "front end" for both the "reflective" and "code-gen" solutions... if the list size is less than 10,000 just reflect it, else code-gen.
    UniversalOnTheFlyCompiledComparatorFactory.java
    package forums;
    import java.util.Comparator;
    import java.lang.reflect.Method;
    import java.lang.reflect.Type;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.Map;
    import java.util.HashMap;
    import javax.tools.DiagnosticCollector;
    import javax.tools.JavaCompiler;
    import javax.tools.JavaFileObject;
    import javax.tools.StandardJavaFileManager;
    import javax.tools.ToolProvider;
    public class UniversalOnTheFlyCompiledComparatorFactory
      public static String DEFAULT_METHOD_NAME = "toString";
      public static String SRC_DIR = "C:/java/home/src/";
      public static String PACKAGE = "forums";
      public static final int DESCENDING = -1;
      public static final int ASCENDING = 1;
      public static int DEFAULT_ORDER = ASCENDING;
      private static final java.lang.Class<?>[] NULL_CLASS_ARRAY = null;
      public static Comparator createComparator(Class classToCompare)
        throws NoSuchMethodException, IOException, CompilationException, ClassNotFoundException, InstantiationException, IllegalAccessException
        return createComparator(classToCompare, DEFAULT_METHOD_NAME, DEFAULT_ORDER);
      public static Comparator createComparator(Class classToCompare, String methodName)
        throws NoSuchMethodException, IOException, CompilationException, ClassNotFoundException, InstantiationException, IllegalAccessException
        return createComparator(classToCompare, methodName, DEFAULT_ORDER);
      public static Comparator createComparator(Class classToCompare, int order)
        throws NoSuchMethodException, IOException, CompilationException, ClassNotFoundException, InstantiationException, IllegalAccessException
        return createComparator(classToCompare, DEFAULT_METHOD_NAME, order);
      public static Map<String,Comparator<?>> cache = new HashMap<String,Comparator<?>>();
      @SuppressWarnings("unchecked")
      public static Comparator createComparator(Class classToCompare, String methodName, int order)
        throws NoSuchMethodException, IOException, CompilationException, ClassNotFoundException, InstantiationException, IllegalAccessException
        final String key = classToCompare.getName()+"."+methodName+"_"+order;
        Comparator<?> comparator = cache.get(key);
        if (comparator != null) {
          return comparator;
        final Method getterMethod = classToCompare.getMethod(methodName, NULL_CLASS_ARRAY);
        final Class returnType = getterMethod.getReturnType();
        if ("void".equals(returnType.getName())) {
          throw new IllegalArgumentException("Cannot compare on the '"+methodName+"' method because its return type is void (ie: it does not return a value to compare).");
        if ( !isComparable(returnType) ) {
          throw new IllegalArgumentException("Cannot compare on the '"+methodName+"' method because its return type '"+returnType.getName()+"' does not implement Comparable.");
        final File javaFile = writeComparatorJava(classToCompare, getterMethod, order);
        if ( ToolProvider.getSystemJavaCompiler().run(null, System.out, System.err, javaFile.getName()) != 0 ) {
          throw new CompilationException("Failed to compile comparator file: "+javaFile.getAbsolutePath());
        final String comparatorClassName = PACKAGE+"."+javaFile.getName().replaceAll("\\.java$", "");
        comparator = (Comparator<?>) Class.forName(comparatorClassName).newInstance();
        cache.put(key, comparator);
        return comparator;
      private static File writeComparatorJava(Class classToCompare, Method getterMethod, int order)
        throws IOException, CompilationException
        final String nameOfClassToCompare = classToCompare.getName().replaceAll("^.*(?=\\.)\\.",""); // remove everything before the last .
        final String getterMethodName = getterMethod.getName();
        final String comparatorClassName = nameOfClassToCompare + getterMethodName.replaceAll("^get","").replaceAll("toString","String") + "Comparator";
        final File comparatorClassFile = new File(SRC_DIR+PACKAGE+"/"+comparatorClassName+".java");
        PrintWriter out = null;
        try {
          out = new PrintWriter(new FileWriter(comparatorClassFile));
          out.println("package "+PACKAGE+";");
          out.println("public class "+comparatorClassName+" implements java.util.Comparator<"+nameOfClassToCompare+">");
          out.println("{");
          out.println("  public static final int DESCENDING = -1;");
          out.println("  public static final int ASCENDING = 1;");
          out.println("  public static final int DEFAULT_ORDER = "+order+";");
          out.println("  public final int order;");
          out.println();
          out.println("  public "+comparatorClassName+"() { this(DEFAULT_ORDER); }");
          out.println();
          out.println("  public "+comparatorClassName+"(int order) { this.order = order; }");
          out.println();
          out.println("  // nulls come last");
          out.println("  public int compare("+nameOfClassToCompare+" a, "+nameOfClassToCompare+" b) {");
          out.println("    if (a==null) {");
          out.println("      return b==null ? 0 : -1;");
          out.println("    } else {");
          out.println("      return b==null ? 1 : a."+getterMethodName+"().compareTo(b."+getterMethodName+"()) * order;");
          out.println("    }");
          out.println("  }");
          out.println();
          out.println("}");
        } finally {
          if (out!=null)out.close();
        return comparatorClassFile;
       * Returns: Does the given clazz implement the given interfaceName
       * @param clazz the Class to be examined.
       * @param canonicalInterfaceName the full name (with or without generics)
       *  of the interface sought: path.to.Interface[<path.to.GenericType>]
      private static boolean isComparable(Class clazz) {
        for ( Type i : clazz.getGenericInterfaces() ) {
          if ( i.toString().startsWith("java.lang.Comparable") ) {
            return true;
        return false;
    UniversalComparatorTest.java
    package forums;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    // A simple "Bean" class for testing only.
    // Does NOT implement comparable!
    class Word {
      private final String word;
      public Word(String word) { this.word=word; }
      public String getWord() {  return this.word; }
      public void noop() { }
      public String toString() { return this.word;  }
      public Word notComparable() { return new Word("notComparable"); }
    class UniversalComparatorTest
      @SuppressWarnings("unchecked")
      public static void main(String[] args) {
        try {
          List<Word> words = readWords("WordFinder.txt");
          System.err.println("---------------------------------------------------");
            long start = System.nanoTime();
            try {
              Comparator<Word> wordComparator = UniversalOnTheFlyCompiledComparatorFactory.createComparator(Word.class);
              Collections.sort(words, wordComparator);
              System.out.println(words);
            } catch (Exception e) {e.printStackTrace();}
            long stop = System.nanoTime();
            System.err.printf("took %6.4f seconds%n", (stop-start)/1000000000.0);
            System.err.println("---------------------------------------------------\n");
            long start = System.nanoTime();
            try {
              Comparator<Word> wordComparator = UniversalOnTheFlyCompiledComparatorFactory.createComparator(Word.class);
              Collections.sort(words, wordComparator);
              System.out.println(words);
            } catch (Exception e) {e.printStackTrace();}
            long stop = System.nanoTime();
            System.err.printf("took %6.4f seconds%n", (stop-start)/1000000000.0);
            System.err.println("---------------------------------------------------\n");
        } catch (Exception e) {
          e.printStackTrace();
       * reads each line of the given file into a List of strings.
       * @param String filename - the name of the file to read
       * @return an List handle ArrayList of strings containing file contents.
      public static List<Word> readWords(String filename) throws FileNotFoundException, IOException {
        List<Word> results = new ArrayList<Word>();
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(filename));
          String line = null;
          while ( (line=reader.readLine()) != null ) {
            results.add(new Word(line));
        } finally {
          if(reader!=null)reader.close();
        return results;
    }Cheers. Keith.
    It's Bed Time ;-)

  • How To: Use reflection to create instance of generic type?

    I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
    My first guess was to write the following:
    Class cls = Class.forName("java.util.ArrayList<String>");
    List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
    Class cls = Class.forName("java.util.ArrayList");
    List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
    If I change the second line to
    List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
    This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
    Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?

    Harald,
    I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
    I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        for ( ...whatever ...) {
           T obj = clazz.newInstance();
           // code to load from storage ...
           list.add(obj);
        return list;
    }And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
    I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
       private static Map<String, Class<? extends Base>> classMap = null;
       static
          Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
          classMap = Collections.synchronizedMap(map);
       public static Class<? extends Base> getClass(String name)
          return classMap.get(name);
       protected static void putClass(Class<? extends Base> cls)
          classMap.put(cls.getName(), cls);
    }And added a static initializer to each of my persistent classes:class Foo extends Base
       static
          Base.putClass(Foo.class);
    }So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
    Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
    Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
    Thanks again for your help,
    Gary

  • Implementing Simulator Using Reflection

    hey my friends,
    I'm working on implementing a Simulator for PIC Microcontroller which executes Assembly instructions and makes appropriate changes in Register File and Memory.
    The way I execute instructions is as follows:
    I have an abstract parent class called Instruction, then I made each individual instruction as separate class that extends Instruction parent class. Now I use reflection to execute each individual instruction by creating a new object of that instruction passing its parameters and then calling execute() method.
    Example :
    MOVE W, 0xFF
    CLRF PORTA
    my Java code will look like :
    Class instructionClass = Class.forName("MOVE");
    Instruction inst = (Instruction) instructionClass.newInstance();
    inst.passParameters(String[] parms);
    inst.execute();
    instructionClass = Class.forName("CLRF");
    inst = (Instruction) instructionClass.forName("PORTA");
    inst.passParameters(String[] parms);
    inst.execute();
    Is there a better fast idea or I shall keep on the same way ?
    Message was edited by:
    HypnotiC
    Message was edited by:
    HypnotiC

    If you know all the types of instruction you could write a method that returns
    an object based on the first word of the line.public abstract class AbstractInstruction {
        protected String[] paramArr;
        protected void setParam(String[] line) {
            paramArr = new String[line.length - 1];
            System.arraycopy(line, 1, paramArr, 0, line.length - 1);
        public abstract void execute();
        public AbstractInstruction create(String[] line) {
            AbstractInstruction ret;
            if(line[0].equals("MOVE")) ret = new MoveInstruction();
            // else if() etc
            else ret = new ClrfInstruction();
            ret.setParam(line);
            return ret;
    class MoveInstruction extends AbstractInstruction {
        public void execute() {
            // do something with paramArr
    class ClrfInstruction extends AbstractInstruction {
        public void execute() {
            // do something else with paramArr
    }

  • Calling a pkg from managed code and then using reflection to call a method from a script task

    Hi we run 2012 std.  I have some pretty good evidence that when I call my pkg from a .net service, a script component in that pkg fails when trying 2 use reflection to load and invoke our .net message history method.  The exception is either on
    the invoke or in the message history method.  I suspect its in the method but will take additional steps 2 verify.
    But when I run the pkg stand alone, it has no problem and the method does what it is supposed 2 do.
    There r no vars passed from the service to the pkg.  I wonder if its a managed to unmanaged to managed issue that the community is already aware of.  If not, my apologies 4 posting this quickly.
    I'll post more info here as I collect it. 

    we have 2 theories after showing the exception trace to folks who r more adept at managed code.
    the first is related to the fact that our 3rd party dlls (I think entity framework is included in these) r older versions.  I don't want to discount this theory but we have some evidence already that this might not be true.
    I hope I can do justice to the 2nd theory but will make it clearer and clearer as I get a better understanding.  I believe this is what Arthur was saying and I applaud his instincts.  They explained that .net is so "smart" that it detected
    a change in namespace  (ie context as Arthur said) and purposely threw an exception 2 save us from ourselves.  The workarounds discussed were a bit over my head but I will continue trying to better understand it.  The fact that many of the methods
    we call after reflection r now merged into one assembly seemed relevant to the discussion and possible workarounds.   
    this link came up in their discussion and I believe the bottom line here is that by qualifying assembly names further (in config?)r, a workaround is possible. 
    http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx  .
    This link came up as well and has something to do with ILMerge and workarounds to ILMerge. 
    http://elegantcode.com/2011/04/02/dynamically-load-embedded-assemblies-because-ilmerge-appeared-to-be-out/  .
    Finally, this link came up and seems to have something to do with embedding your dlls in one assembly without them losing their identity.
    http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx
    I'll post more here as we muddle thru this.

Maybe you are looking for