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

Similar Messages

  • Working around unchecked conversions when using reflection

    I think I've convinced myself that there's no way around this issue when using reflection and Generics, but here's the issue:
    Suppose I've got a method that uses reflection to compare an arbitrary property in
    an arbitrary pair of beans (of the same class).
    public static <T> int compare(T bean0, T bean1, String prop) throws Exception {
         Method m = bean0.getClass().getMethod(
                   "get" + prop.substring(0,1).toUpperCase() +
                   prop.substring(1));
         Object o0 = m.invoke(bean0);
         Object o1 = m.invoke(bean1);
         if (o0 instanceof Comparable &&
             o1 instanceof Comparable &&
             (o1.getClass().isAssignableFrom(o0.getClass()) ||
              o0.getClass().isAssignableFrom(o1.getClass()))) {
              return ((Comparable)o0).compareTo(o1); // compiler warning
         } else {
              return o0.toString().compareTo(o1.toString());
    }There's no way that, in general, when using reflection to invoke methods, that you can coerce the types to avoid compile-time type safety warnings. I think the above code is guarranteed not to throw a runtime ClassCastException, but there's no way to write the code so that the compiler can guarrantee it. At least that's what I think. Am I wrong?

    Ok it looks like you're dealing with a classloader issue. when you call that method, it is the equivelant of calling
    Class.forName("Box", true, this.getClass().getClassLoader())The exception is thrown when your class's classloader cannot find the class box. try putting 'null' there
    Class.forName("Box", true, null)and it will request the bootstrap classloader to load the class. just make sure you have permission :
    If the loader is null, and a security manager is present, and the caller's class loader is not null, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the bootstrap class loader. (copied from the API)

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

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

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

  • Using reflection...

    Hi,
    I have one class. to run that, I am calling like the following...
    java -classpath ;.;\comdotebo; com.pack1.MyClass
    now I want to take the reference of this class(dynamically) using reflection pakcage like the following...
    Class cla = Class.forName("com.pack1.MyClass");
    but to take the class reference I need to set the classpath;
    so how can i set the classpath dynamically.
    please give proper solution
    thanks
    Raja Ramesh Kumar M

    here the case is we know both the class and the class path at run time only
    for ex: see the following.....
    I have two files .....
    1) c:\dir1\com\pack1\MyClass1.class
    2) c:\dir2\com\pack2\MyClass2.class
    now I want to access both the classes using reflection from ...
    c:\dir3\com\pack3\MainClass.class
    using reflection, we can write the following...
    Class clas1 = Class.forName("com.pack1.MyClass1");
    if I am taking like this, then I am getting ClassNotFoundException.
    becoz, for that we have to give the proper classpath before running the program.
    like.
    set classpath=%classpath%;.;c:\dir1;
    but my problem is here I know the the class name (for ex: com.pack1.MyClass1) and the classpath (ex: c:\dir1)
    at runtime only.
    so please tell me how to solve this problem
    regards
    Raja Ramesh Kumar

  • Same Multi comparator used in 2 different popups

    Hi,
    I am using a multi comparator to do a sorting for the search results in a pop screen for a customer details.Here is the code
    class MultiComparator<T> implements Comparator<CustomerVO> {
    public int compare(CustomerVO o1, CustomerVO o2) {
    int i = o1.getCustId().compareTo(o2.getCustId()); // primary
    int j = o1.getCustName().compareTo(o2.getCustName()); // secondary
    if (i > 0) {
    return 1;
    } else if (i < 0) {
    return -1;
    } else {
    if (j > 0) {
    return 1;
    } else if (j < 0) {
    return -1;
    } else {
    return 0;
    if (sortColumn == null) {
    Collections.sort(searchList, new MultiComparator<CustomerVO>());
    This is fine for the selected popup screen which is displaying the customer details.
    Now i need to use the same comparator for another popup screen which is displaying customers contact details
    but importantly it does have the custId and CustName fields displayed in that popup. In such case how i can use the
    same Comparator for displaying the contacts details as they dont include the custId and custName which is a
    part of the Comparator. I hope i am clear with my question.
    Thanks.

    Thanks Sabre for the templated class , that was a typo. How can i use the same comparator used for customer screen popup for another popup screen which displays contact details but doesnot have the custId & custName fields. Hence how can i retain the same ordering of customer screen popup (using multi comparator) for contact details?

  • How to create an array using reflection.

    How to create an array using reflection.
    I want to achive something like this,Object o;
    o = (Object)(new TestClass[10]);but by use of reflection.
    To create a single object is simple:Object o;
    o = Class.forName("TestClass").newInstance();But how do I create an array of objects, when the class of objects is known only by name? (Can't use Object[] because even though an Object[] array can be filled with "TestClass" elements only, it Cannot be casted to a TestClass[] array)
    Anybody knows?":-)
    Ragnvald Barth
    Software enigneer

    Found it!
    the java.lang.reflect.Array class solves it!
    Yes !!!

  • 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

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

  • Get Name of Variable using Reflection

    Is there a way to get the variable name?  I assume I'd have to use Reflection.  Here's an example of what I mean.
    Dim tileCount As Integer
    ' get tileCount variable name here
    Debug.Print("tileCount")
    Ryan

    I need to validate a variable.  If the variable isn't valid I want to throw an ArgumentOutOfRangeException.
    Variable names are internal to your program.  They don't actually exist as part of your executable code, but it is possible with reflection to look back into the source code and find certain information.   But it is not possible
    to identify a variable by its value. However, you should not be using variable names to identify your objects.
    If you create a class for your values then you can build a IsValid test for the value field of the class, and return information about the class instance.  For example:
    Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim thisTile As New Tile With {.Height = 7, .Name = "Fred"}
    If Not thisTile.IsValidHeight Then
    Throw New ArgumentOutOfRangeException("Instance", thisTile.Name, String.Format("{0} is not a valid tile height.", thisTile.Name))
    End If
    End Sub
    End Class
    Public Class Tile
    Public Name As String
    Public Height As Integer
    Public Function IsValidHeight() As Boolean
    Dim myArray() As Integer = {3, 4, 6, 7}
    If Not myArray.Contains(Me.Height) Then
    Return True
    Else
    Return False
    End If
    End Function
    End Class
    Great idea! :)
    Still lost in code, just at a little higher level.

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

  • What Universe was used to create a report?

    Is there any way to tell what Universe was used to create a specific report, Also is there anyway to tell what Universe connection a specific Universe is using?
    Thanks
    jeff

    Hey Ted,
    Thanks but I got an error when I tried to do this. Here is the query that I used. Any thoughts?
    Select * from CI_APPOBJECTS WHere SI_KIND='Universe' And SI_CUID='<ASBJCyAKjL1FhG1pNAMsor4>'.
    and here is the error
    A potentially dangerous Request.Form value was detected from the client (sqlStmt="... SI_CUID='<ASBJCyAKjL1FhG1pNAM...").
    Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.
    Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (sqlStmt="... SI_CUID='<ASBJCyAKjL1FhG1pNAM...").
    Thank you!
    jeff

  • Problem using reflection... Really urgent...

    Hi all,
    in my current program, i'm usin reflection a lot. This is due to the fact that i automatically generate some code, compile it, and run another program which uses the generated code.
    The generated code contains inner classes. For example:
    package mypackage;
    class A {
    public A() {}
    class B {
    public B() {}
    class C {
    public C() {}
    My question is: how can i instantiate, the classes B and C using reflection? i think i tried everything but when i run my prog i keep having error messages such as:
    - InstantiationException
    - NoSuchMethodException
    -etc...
    Any idea?
    Jack

    Consider this:
    Can you make the inner clases static? If you do, you may instatiate them by using names like A.B and A.B.C.
    If the inner classes are not made static, they need an instance of the enclosing class in order to be instantiated. This basically means that you may instantiate a B from inside a (non-static) method (or constructor) in A, and a C from within a method in B.
    One way of doing this is to create a method on A that creates a B (a factory method). Then, in order to get a B you first create an A, then call the factory method to get a B. By putting a factory method for C's in B, you could then go on to create a C from the B.
    But before going into this, you should consider whether you really need the inner classes to be non-static.

  • My University email uses outlook and firefox will not let the page open once i log into the university login. It used to work, but now just shows a completely white tab. My email works fine in other browsers. Why?

    My University email uses outlook and firefox will not let the page open once i log into the university login. It used to work, but now just shows a completely white tab. My email works fine in other browsers. Why?

    Make sure that you haven't left a profiles.ini file.
    * http://kb.mozillazine.org/profiles.ini_file
    *http://kb.mozillazine.org/Profile_folder_-_Firefox

Maybe you are looking for

  • Error while approving work item

    Hi All, I am getting error while approving a claim request; error is: error while inserting claim record xxxxxxx in cluster for employee xxxxxxxx This does not happen always, some time I am able to approve and sometime i got the error. I am using sam

  • Error on the SAP BPC patches

    Dear SAP Support, I used the SAP BPC 5.1 SP 3 and Ms.SQL Server 2005 SP 2 in my dev environment , I have upgrade it to be SP 11 and Ms.SQL Server 2005 SP3. SAP BPC upgrade for server, Administration, and Client(office) ran perfectly and based on the

  • JDev BUG? XmlInvalidOnCommitException

    Hello Everyone, I tried to run the Business Components From Tables assistant for two tables, DESIGN_REQUEST and COMMERCIAL_REFERENCE_REQUEST, and created a new package (...model.designrequest) to store my brand new Entity Objects and their associatio

  • MIRO - One line and two Tax codes

    Hello dear all, If I have a reception (MIGO), one line item. But in the supplier invoice this line has two tax codes. How can we post it in MIRO, what can be the process ? Is anyone had similar case ? Regards

  • Check for zero

    I am looking for a way to check input fields for zero values in my action listener and bring up a message dialog if it finds one. I can get it to look for null or alpha characters but I can't figure out how to look for zero. Any suggestion would be a