I bumped recently (twice) at following problem - is it possible to find on classpath specific implementation of generic interface? To visualize this please consider these snippets of code:    public interface Cleaner&lt;T extends Room&gt; {} public class KitchenCleaner implements Cleaner&lt;Kitchen&gt; {} public class BathroomCleaner implements Cleaner&lt;Bathroom&gt; {}   Now - Is it possible to have a following method ?:  public static &lt;T extends Room&gt; findCleanerServiceForRoomType(T room) {     return ??? }   returning KitchenCleaner for Kitchen class and BathroomCleaner for Bathroom class? Of course I would like to have it extensible so that when new Room and Service type is added this method still works... So no switches or ifs :)
70070
Can I do it with reflection or something like that?
5986
Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no (due to type erasure), but I'd be interested if anyone can see something I'm missing:  class SomeContainer&lt;E&gt; {     E createContents()     {         return what???     } }   EDIT: It turns out that  could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.  I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's .
55652
public interface IBar {}  public interface IFoo : IBar {}  typeof(IFoo).BaseType == null   How can I get IBar?
93303
If I have the following code: MyType&lt;int&gt; anInstance = new MyType&lt;int&gt;(); Type type = anInstance.GetType();  How can I find out which type argument(s) &quot;anInstance&quot; was instantiated with, by looking at the type variable? Is it possible?
6832
How does one go about and try to find all subclasses of a given class (or all implementors of a given interface) in Java? As of now, I have a method to do this, but I find it quite inefficient (to say the least). The method is:    Get a list of all class names that exist on the class path Load each class and test to see if it is a subclass or implementor of the desired class or interface   In Eclipse, there is a nice feature called the Type Hierarchy that manages to show this quite efficiently. How does one go about and do it programmatically?
57326
I noticed that the generic IEnumerator&lt;T&gt; inherits from IDisposable, but the non-generic interface IEnumerator does not. Why is it designed in this way?  Usually, we use foreach statement to go through a IEnumerator&lt;T&gt; instance. The generated code of foreach actually has try-finally block that invokes Dispose() in finally.
25861
What is the best way of searching the whole classpath for an annotated class?  I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.  Do you know a library or a Java facility to do this?  Edit: I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with @WebService or @EJB and the system finds these classes while loading so they are accessible remotely.
79010
Take the following class as an example:  class Sometype {     int someValue;      public Sometype(int someValue)     {         this.someValue = someValue;     } }   I then want to create an instance of this type using reflection:  Type t = typeof(Sometype); object o = Activator.CreateInstance(t);   Normally this will work, however because SomeType has not defined a parameterless constructor, the call to Activator.CreateInstance will throw an exception of type MissingMethodException with the message "No parameterless constructor defined for this object." Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes.
36889
Is it possible to have an anonymous type implement an interface?  I've got a piece of code that I would like to work, but don't know how to do this.  I've had a couple of answers that either say no, or create a class that implements the interface construct new instances of that. This isn't really ideal, but I'm wondering if there is a mechanism to create a thin dynamic class on top of an interface which would make this simple.  public interface DummyInterface {     string A { get; }     string B { get; } }  public class DummySource {     public string A { get; set; }     public string C { get; set; }     public string D { get; set; } }  public class Test {     public void WillThisWork()     {         var source = new DummySource[0];         var values = from value in source                      select new                      {                          A = value.A,                          B = value.C + "_" + value.D                      };          DoSomethingWithDummyInterface(values);      }      public void DoSomethingWithDummyInterface(IEnumerable&lt;DummyInterface&gt; values)     {         foreach (var value in values)         {             Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);         }     } }   I've found an article  that describes one approach. Is this the best way of doing this?
25516
I have heard that the Java implementation of Generics is not as good as the C# implementation. In that the syntax looks similar, what is it that is substandard about the Java implementation, or is it a religious point of view?
120216
This is probably not possible, but I have this class:  public class Metadata&lt;DataType&gt; where DataType : struct {     private DataType mDataType; }   There's more to it, but let's keep it simple.  The generic type (DataType) is limited to value types by the where statement.  What I want to do is have a list of these Metadata objects of varying types (DataType).  Such as:  List&lt;Metadata&gt; metadataObjects; metadataObjects.Add(new Metadata&lt;int&gt;()); metadataObjects.Add(new Metadata&lt;bool&gt;()); metadataObjects.Add(new Metadata&lt;double&gt;());   Is this even possible?
69502
Possible Duplicate:          Would someone explain the differences between these two beasts and how to use them. AFAIK, many  pre.2.0 classes were implemented without generic types, thus causing latter version to implement both flavors of interfaces. Is the the only case why one would need to use them?  Can you also explain in depth how to use them.?  Thanks
30764
We need to get all the instances of objects that implement a given interface - can we do that, and if so how?
3079
In C# is there a technique using reflection to determine if a method has been added to a class as an extension method?  Given an extension method such as the one shown below is it possible to determine that Reverse() has been added to the string class?  public static class StringExtensions {     public static string Reverse(this string value)     {         char[] cArray = value.ToCharArray();         Array.Reverse(cArray);         return new string(cArray);     } }   We're looking for a mechanism to determine in unit testing that the extension method was appropriately added by the developer.  One reason to attempt this is that it is possible that a similar method would be added to the actual class by the developer and, if it was, the compiler will pick that method up.
22377
Some time ago, I came across a piece of code, that used some piece of standard Java functionality to locate the classes that implemented a given interface. I know the functions were hidden in some non-logical place, but they could be used for other classes as the package name implied. Back then I did not need it, so I forgot about it, but now I do, and I can't seem to find the functions again. Where can these functions be found?  Edit: I'm not looking for any IDE functions or anything, but rather something that can be executed within the Java application.
85933
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.  Getting the field names is fairly simple, here is what a co-worker came up with:  public static List initFieldArray(String className) throws ClassNotFoundException {      Class c = Class.forName(className);     Field field[] = c.getFields();     List&lt;String&gt; classFields = new ArrayList(field.length);      for (int i = 0; i &lt; field.length; i++) {         String cf = field[i].toString();         classFields.add(cf.substring(cf.lastIndexOf(".") + 1));     }      return classFields; }   Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.  Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.
18992
I'm developing an application where I the need to invoke a method of a generic class and I don't care about the instances actual type. Something like the following Java code:  public class Item&lt;T&gt;{   private T item;    public doSomething(){...} }  ... public void processItems(Item&lt;?&gt;[] items){  for(Item&lt;?&gt; item : items)    item.doSomething(); }   At the time I was on a hurry, so I solved my problem by defining a interface with the methods I needed to invoke and made the generic class implement it.  public interface IItem   {    void doSomething(); }  public class Item&lt;T&gt; : IItem {   private T item;    public void doSomething(){...} }  ... public void processItems(IItem[] items) {  foreach(IItem item in items)    item.doSomething(); }   This workaround works fine, but I'd like to know what is the correct way to achieve the same behavior.    EDIT:  I forgot to refer that the caller of processItems doesn't know the actual types. Actually the idea was that the array passed as argument to processItems could contain intermixed types. Since its not possible to have such an array in .Net, using a non generic base class or interface seems to be the only way.