Enums and generic classes

Hi all,
consider the following class:
public class Box<T> {
  // omitted
}Suppose I create an Enum like so:
public enum BoxEnum {
    FIRST_BOX("Box1", String.class), SECOND_BOX("Box2", Integer.class);
    private final String name;
    private final Class<?> classType;
    // The starting point of the problem
    private static Map<String, Box<?>> map;
    static {
        map = new Hashtable<String, Box<?>>();
        for (BoxEnum i : BoxEnum.values()) {
            map.put(i.getName(), new Box<Same Type as classType>());
            // note the error in the upper line
    BoxEnum(String name, Class<?> classType) {
        this.name = name;
        this.classType = classType;
    public String getName() {
        return name;
    @SuppressWarnings("unchecked")
    public <T> T getClassType() {
        return (T) classType;
}Note where the problem occurs; what I am trying to achieve is to populate a Map. Moreover, I should be able to create a new Box holding the exact same data that is specified in the Enum constant. To be more precise, consider the following example:
FIRST_BOX("Box1", String.class)the program should populate a Map so that the key would be "Box1" and the value would be "new Box<String>()".
Is there a way to achieve this?
Thank you.

Hi, thank you for a quick response.
I'm not really sure if I understand your reply correctly, or maybe I was not clear enough describing my question. I did try a few different approaches with your suggestion but none of them worked, so I'll try to show one more example, to make this clearer (or so I hope)
// This is where it goes down:
private static Map<String, Box<?>> map;
    static {
        map = new Hashtable<String, Box<?>>();
        for (BoxEnum i : BoxEnum.values()) {
            // This is the fundamental part; this is where the new Box
            // should be created, having the same data type as its
            // enum constant, thus if i == 0, then:
            String name = i.getName();  // "Box1"
            Class<?> cls = i.getClassType() // this method was corrected, please note below
            map.put(name, new Box<cls>());  // please note the cls variable; here's the error
  // the corrected method
public <T> T getClassType() {
        return (T) classType.newInstance();
}

Similar Messages

  • Are enums and inner classes allowed in taglib function signatures??

    Hi,
    I have a taglib with the following function definition:
    <function>
            <description>Determine if viewing a patient attribute is allowed</description>
            <name>isViewingPatientAttributeAllowed</name>
            <function-class>com.example.admin.authorization.UserAuthorizer</function-class>
            <function-signature>boolean isViewingPatientAttributeAllowed(com.example.bean.User, com.example.bean.Patient.PatientAttribute, com.example.bean.Patient)</function-signature>
            <example>
                ${ncvi:isViewingPatientAttributeAllowed(user, patientAttribute, patient)}
            </example>
    </function>Where com.example.bean.Patient.PatientAttribute is an enum (note package names have been changed to protect the innocent;-). When I try to compile my web app I get the following error:
    org.apache.jasper.JasperException: The class com.example.bean.Patient.PatientAttribute specified in the method signature in TLD for the function ncvi:isViewingPatientAttributeAllowed cannot be found. com.example.bean.Patient.PatientAttributeIf I change PatientAttribute to a static inner class of Patient, I still get the error. Are enums and inner classes allowed in function signatures?
    Thx.

    I think that you'll find it easier to define a non-inner abstract class RefBase, that exposes a removeFromQueue() method, then extend that for your Ref class. That way, the queue just deals with RefBase instances (or ? extends RefBase).
    I think that any other approach is going to get the compiler confused, because the compile-time Ref depends on the parameterization of its defining class.

  • Using static .values() method of Enum in Generic Class

    Hi *,
    I tried to do the following:
    public class AClass<E extends Enum<E> >  {
         public AClass() {
              E[] values = E.values(); // this DOESN'T work
              for (E e : values) { /* do something */ }
    }This is not possible. But how can I access all Enum constants if I use
    an Enum type parameter in a Generic class?
    Thanks for your help ;-) Stephan

    Here's a possible workaround. The generic class isn't adding much in this case; I originally wrote it as a static method that you simply passed the class to:
    public class Test21
      public static enum TestEnum { A, B, C };
      public static class AClass<E extends Enum<E>>
        private Class<E> clazz;
        public AClass(Class<E> _clazz)
        {  clazz = _clazz;  }
        public Class<E> getClazz()
        {  return clazz;  }
        public void printConstants()
          for (E e : clazz.getEnumConstants())
            System.out.println(e.toString());
      public static void main(String[] argv)
        AClass<TestEnum> a = new AClass<TestEnum>(TestEnum.class);
        a.printConstants();
    }

  • Problem in generic value copier class / reflection and generic classes

    Hello experts,
    I try to archive the following and am struggling for quite some time now. Can someone please give an assessment if this is possible:
    I am trying to write a generic data copy method. It searches for all (parameterless) getter methods in the source object that have a corresponding setter method (with same name but prefixed by "set" instead of "get" and with exactly one parameter) in the destination object.
    For each pair I found I do the following: If the param of the setter type (T2) is assignable from the return type of the getter (T1), I just assign the value. If the types are not compatible, I want to instantiate a new instance of T2, assign it via the setter, and invoke copyData recursively on the object I get from the getter (as source) and the newly created instance (as destination). The assumption is here, that the occurring source and destination objects are incompatible but have matching getter and setter names and at the leaves of the object tree, the types of the getters and setters are compatible so that the recursion ends.
    The core of the problem I am struggling with is the step where I instantiate the new destination object. If T2 is a non-generic type, this is straightforward. However, imagine T1 and T2 are parametrized collections: T1 is List<T3> and T2 is List<T4>. Then I need special handling of the collection. I can easily iterate over the elements of the source List and get the types of the elements, but I can not instantiate only a generic version of the destinatino List. Further I cannot create elements of T4 and add it to the list of T2 and go into recursion, since the information that the inner type of the destination list is T4 is not available at run-time.
    public class Source {
       T1 getA();
       setA(T1 x);
    public class Dest {
       T2 getA();
       setA(T2 x);
    public class BeanDataCopier {
       public static void copyData(Object source, Object destination) {
          for (Method getterMethod : sourceGetterMethods) {
             ... // find matching getter and setter names
             Class sourceParamT = [class of return value of the getter];
             Class destParamT = [class of single param of the setter];
             // special handling for collections -  I could use some help here
             // if types are not compatible
             Object destParam = destination.getClass().newInstance();
             Object sourceParam = source.[invoke getter method];
             copyData(sourceParam, destParam);
    // usage of the method
    Souce s = new Source(); // this is an example, I do not know the type of s at copying time
    Dest d = new Dest(); // the same is true for d
    // initialize s in a complicated way (actually JAX-B does this)
    // copy values of s to d
    BeanDataCopier.copyData(s, d);
    // now d should have copied values from s Can you provide me with any alternative approaches to implement this "duck typing" behaviour on copying properties?
    Best regards,
    Patrik
    PS: You might have guessed my overall use case: I am sending an object tree over a web service. On the server side, the web service operation has a deeply nested object structure as the return type. On the client side, these resulting object tree has instances not of the original classes, but of client classes generated by axis. The original and generated classes are of different types but have the identically named getter and setter methods (which again have incompatible parameter types that however have consistent names). On the client side, I want to simply create an object of the original class and have the values of the client object (including the whole object tree) copied into it.
    Edited by: Patrik_Spiess on Sep 3, 2008 5:09 AM

    As I understand your use case this is already supported by Axis with beanMapping [http://ws.apache.org/axis/java/user-guide.html#EncodingYourBeansTheBeanSerializer]
    - Roy

  • New in Kodo 3.3.3: Improved support for Java 5 enums and generics?

    Hello,
    Can anybody tell me if Kodo 3.3.3 can be deployed on WebLogic 8.1 sp4, jdk
    1.4.1? The reason I ask this is because one of the features mentioned for
    v3.3.3 is the support for Java 5 generics, which is available on WebLogic
    9 -- but not in WebLogic 8.1 sp4. The documentation for Kodo 3.3.3 seems
    to indicate that it can be deployed on WebLogic 8.1 -- can anyone tell me
    if this is accurate?
    Thanks for your help!

    Correction:
    I think that my question may have been misunderstood. What I want to know
    is if Kodo 3.3.3 can be deployed on WebLogic 8.1sp4 which is running JDK
    1.4 or do I have to deploy on a newer version of WebLogic that is running
    Java 5?
    Thanks!
    Rita wrote:
    I think that my question may have been misunderstood. What I want to know
    is if Kodo 3.3.3 can be deployed on WebLogic 8.1sp4 which is running JDK
    1.4 or do I have to deploy on a newer version of WebLogic that is running
    Java 4?
    Thanks!
    Stephen Kim wrote:
    Rita,
    While Kodo 3.3.x can work with JDK 5, it cannot make WL work with JDK 5.
    However, Kodo 3.4 RC 3 / 4.0 EA 2 both can work with WL 9 (which works
    with JDK 5).
    Rita wrote:
    Hello,
    Can anybody tell me if Kodo 3.3.3 can be deployed on WebLogic 8.1 sp4,
    jdk
    1.4.1? The reason I ask this is because one of the features mentionedfor
    v3.3.3 is the support for Java 5 generics, which is available on WebLogic
    9 -- but not in WebLogic 8.1 sp4. The documentation for Kodo 3.3.3 seems
    to indicate that it can be deployed on WebLogic 8.1 -- can anyone tell me
    if this is accurate?
    Thanks for your help!
    Steve Kim
    [email protected]
    SolarMetric Inc.
    http://www.solarmetric.com

  • Working with traits and policy classes

    I have not been able to see if anyone has raised this before from my searches of the forums but this may just be bad searching !
    I am trying to investigate how much of the traits / policies idioms of working in C++ generic programming are applicable to Java. The following trio of classes are a very striped down version of one problem I am having. It relates to the use of static methods, inheritance and generic classes.
    First a couple of classes with static methods related by inheritance.
    public class X {
      public static int get() {
        System.err.println("X.get.") ;
        return 1 ;
    public class Y extends X {
      public static int get() {
        System.err.println("Y.get.") ;
        return X.get() + 1 ;
    }Now a class that uses the types as type parameters and tries to call the static method:
    public class TypeParameterLookupSolved<A extends X> {
      private void doit() {
        System.out.println(A.get()) ;
      public static void main(final String[] args) {
        TypeParameterLookupSolved<Y> tpli = new TypeParameterLookupSolved<Y> () ;
        tpli.doit() ;
    }The output from running this is:
    X.get.
    1
    So the question is why does the call of A.get() always bind to X.get() when na�vely you would expect Y.get() to be called.
    If Java will only ever call X.get() in this instance then the policy class idiom will not work properly . Of course it may be that there is another way of doing this that I have missed.
    Thanks.

    Thanks for the correction.
    I never can get the hang of up and down in type hierarchies -- functional programming people talk a lot about top and bottom in type hierarchies and I never remember which is which. One of these days I will find a mechanism for putting the knowledge into long-term memory :-)
    Having had the epiphany of "least upper bounds", it is now trivially easy to do Java-style generic programming (which is good :-) even though it is totally different to everyone else (C++, Python, Groovy, Ruby, Nice, CL, OCAML, Haskell, . . .-- which is not so good). I am increasingly of the view that using the term Generics has been a labelling error and an unfortunate disservice to Java as it can set up a mind-set about parameterized types and "generic programming" that is fundamentally wrong. I can feel a series of short articles coming on as well as sorting out my ADS library!

  • Javadoc, generics and inner classes

    I have implemented a generic class DiGraph with inner classes Vertex and Edge:
    public class DiGraph<V,E> implements Iterable<DiGraph<V,E>.Vertex> {
       public Vertex addVertex(V value) {...}
       public Iterator<DiGraph<V,E>.Vertex> iterator() {... }
       public class Vertex implements Iterable<Edge>  {
          V value;
       public class Edge {
          E  value;
    }When i run Javadoc it yields the following documentation of the class DiGraph :
    public class DiGraph extends Object implements Iterable<DiGraph.Vertex>What I expected was
    public class DiGraph extends Object implements Iterable<DiGraph<V,E>.Vertex>In a similar way the method addVertex appears as:
    public DiGraph.Vertex addVertex(V value)instead of
    public DiGraph<V,E>.Vertex addVertex(V value)This is very confusing, because if I create a graph
    DiGraph<String,Integer> myGraph and the use e.g., the method addVertex I must write:
    DiGraph<String,Integer>.Vertex v = myGraph.addVertex("a");Can anyone explain why the documentation lacks <V,E> ?

    One more dumbshit question...
    Is there a way to do this without the warnings OR the @SuppressWarnings({"unchecked"})
       * Returns the index of the last occurrence of the specified element in this
       * list, or -1 if this list does not contain the element.
      //@SuppressWarnings({"unchecked"})
      public int lastIndexOf(Object object) {
        int i = 0;
        int last = -1;
        for(Node<E> node=this.head.next; node!=null; node=node.next) {
          if (node.item.equals((E) object)) {
            last = i;
          i++;
        return(last);
    produces the warning
    C:\Java\home\src\linkedlist\LinkedList.java:313: warning: [unchecked] unchecked cast
    found   : java.lang.Object
    required: E
          if (node.item.equals((E) object)) {
                                   ^... remembering that List specifies +public int lastIndexOf(Object object);+ as taking a raw Object, not E element, as I would have expected.
    Thanx all. Keith.

  • Generic classes with parameterized super class and interface

    Hello.
    I'm trying to write a generic class that looks like the following pseudo-code.
    public interface Interface {
        public Interface getSibling(...);
    public class Klass {...}
    public class MyKlass<T extends Klass, T2 extends Interface>
            extends T implements T2 {
        public T2 getSibling(...) {
            return this;
    }where Interface and Klass each have various extensions.
    I came across this problem, or challenge, while writing classes for testing my EJBs. I tried and failed various attempts.
    Is it possible to write generic classes of this nature in Java?
    If so, please tell me and others who are like me.
    Thanks in advance.

    No. That would not work.
    Beside being forbidden by the compiler, to my understanding, it cannot be done in theory either, as the parameterized types get bound at instantiation time and are not available for static reference, which both extends and implements require.

  • Mixing generic and concrete classes

    I am going over the generics tutorial by Gilad Bracha offered by Sun. Something strikes me as wrong
    Collection c;
    Collection<Part> k = c; //compile-time unchecked warning
    Collection<Part> k = (Collection<Part>) c; //compile-time unchecked warningFor me, the first unchecked warning is mildly acceptable, but my honest opinion is it should be an error not a warning. Isint this effectively an automatic narrowing cast? I personally like my cases to be inside of (), and not hidden. I could be wrong.
    The second unchecked warning however should not even be given. If the 2nd warning is acceptable, then why not flag all casts as 'unchecked warnings?'
    I have a feeling this has to do with this 'erasure' stuff and the resultant class files. I would appreciate any light you could shed on this for me.

    Well Java is really a hobby for me and i end up doing other stuff for several months at a time. And now I am back into Java. I'm finding that I usually do it in the fall and winter, strange..
    Plus 1.5 is so exciting, I'm like a baby all over again with so much to learn!
    I am learning that generics is all compile-time, so I kind of understand that there is really no such thing as casting a generic type. Or that it makes no sense since casting and generics live in different "times" for lack of a better term.
    I think i get it. The second would give the false impression that a cast is actually taking place, and would thus pollute the notion of casting with this fake cast. And the first is not a warning about that line in particular, but a warning about the fact that you are taking your type-safety into your own hands when you subvert the system in this fashion. Which also applies to the second. In fact the cast is immaterial.
    OK, I see now how they are the same thing. But why is generic casting even allowed if its meaningless?

  • Generic classes and the catch block

    Is there a reason why the catch block doesn't work with generic classes?

    JLS 8.1.2:
    <quote>
    It is a compile-time error if a generic class is a direct or indirect subclass of Throwable.
    </quote>
    <quote>
    This restriction is needed since the catch mechanism of the Java virtual machine works only with non-generic classes.
    </quote>
    I guess they didn't feel a need to tinker with the JVM definition to achieve that.
    Too slow!
    Message was edited by:
    DrLaszloJamf

  • Hp LaserJet 1200 Generic Class: Waiting for device

    I have 2 computers that I want to print to my hp Laserjet 1200 printer. We are using an iogear 4-port usb 2.0 sharing switch. One computer prints fine but the other always displays a message "Generic Class: Waiting for device." Help!

    Both computers have the printer driver installed. The usb device does not have a driver to install. You just plug in the usb cords to each computer and the printer. You only install a driver if using a pc operating system.

  • Best way to call a function in a generic class from a base class

    Hi,
    I have a generic class that works with subclasses of some other baseclass. When I construct the subclass, I call the constructor of the baseclass which I want to call a function in the generic class. e.g. suppose I have the following classes
    public class List<T extends BaseClass>
        newTCreated(T t)
    }

    Sorry, I pressed Tab and Enter last time when typing the code so I posted without meaning to
    Hi,
    I have a generic class that works with subclasses of some other baseclass. When I construct the subclass, I call the constructor of the baseclass which I want to call a function in the generic class. e.g. suppose I have the following classes
    public class List<T extends BaseClass>
        public void newTCreated(T t)
            // add the t to some internal list
        public T getT(int index)
            // get the object from the internal list
    public class BaseClass
        public BaseClass(List<?> list)
            list.newTCreated(this);
    public class SubClass extends BaseClass
        public SubClass(List<SubCass> list)
            super(list);
    }This doesn't compile because of the call to newTCreated in the BaseClass constructor because BaseClass is not necessarily of type T. Is there any way of checking when I call the newTCreated function that the BaseClass is actually of type SubClass? I could either add the call explicitly in each SubClass's constructor or have a function addToList in BaseClass that is called from the BaseClass constructor but overloaded in each subclass but both of those rely on future subclasses doing the same. Or I could change the newTCreated function to take an argument of type BaseClass and then cast it to type T but this doesn't give a compilation error, only a runtime exception.
    It seems like there should be solution but having only recently started writing Generic classes I can't find it. Thanks in advance for any help,
    Tom

  • Getting the name of the generic class?

    I have a generic class declared as such:
    public class MyClass<T>
    and I want to access the name of the <T> class a member function in that class? I just can't figure out which syntax to use.
    Thank you!
    Joshua

    Sorry, I'm a little bit confused at your answer.
    I cannot seem to instantiate an object of class T, like: T item = new T();does not work. If I can't create an object of type T, then I can't get it's type. I need to get the class even if I don't have any instantiated objects (or if I can create a blank one), so that I can use the name to fetch the objects from the persistence engine. Here is the class, so you can see what I'm talking about. I have in there now what seems like it should be right, but doesn't compile.
    A small example of solution please?
    public class PersistentSelectorCellEditor<T> extends AbstractCellEditor
              implements TableCellEditor {
         JComboBox control;
         List<T> choices;
         Session session;
         public PersistentSelectorCellEditor() {
              initializeComponents();
         public PersistentSelectorCellEditor(Object value) {
              initializeComponents();
              this.control.setSelectedItem(value);
         private void initializePersistence() {
              session = LabApp.getSession();
              session.beginTransaction();
         private void initializeComponents() {
              initializePersistence();
              populateList();     //query for selections to fill combo box
              control = new JComboBox((ComboBoxModel)choices);
         private void populateList() {
              //query to populate drop down lists
              Query query = session.createQuery("from " + T.class.getName());
              choices = query.list();
         public void setValue(T value) {
              control.setSelectedItem(value);
         public T getValue() {
              return (T)control.getSelectedItem();
         //interface members
         public Object getCellEditorValue() {
              return control.getSelectedItem();
         public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
              return control;
    }Thank you!
    Joshua

  • What is the use of Generic class in java

    hi everyone,
    i want to know that
    what is the use of Generic class in java ?
    regards,
    dhruvang

    Simplistically...
    A method is a block of code that makes some Objects in the block of code abstract (those abstract Objects are the parameters of the method). This allows us to reuse the method passing in different Objects (arguments) each time.
    In a similar way, Generics allows us to take a Class and make some of the types in the class abstract. (These types are the type parameters of the class). This allows us to reuse the class, passing in different types each time we use it.
    We write type parameters (when we declare) and type arguments (when we use) inside < >.
    For example the List class has a Type Parameter which makes the type of the things in the list become abstract.
    A List<String> is a list of Strings, it has a method "void add(String)" and a method "String get(int)".
    A List<File> is a list of Files, it has a method "void add(File)" and a method "File get(int)".
    List is just one class (interface actually but don't worry about that), but we can specify different type arguments which means the methods use this abstract type rather than a fixed concrete type in their declarations.
    Why?
    You spend a little more effort describing your types (List<String> instead of just List), and as a benefit, you, and anyone else who reads your code, and the compiler (which also reads your code) know more accurately the types of things. Because more detail is known, the compiler is able to tell you when you screw up (as opposed to finding out at runtime). And people understand your code better.
    Once you get used to them, its a bit like the difference between black and white TV, and colour TV. When you see code that doesn't specify the type parameters, you just get the feeling that you are missing out on something. When I see an API with List as a return type or argument type, I think "List of what?". When I see List<String>, I know much more about that parameter or return type.
    Bruce

  • XI: How To Use JAVA generic Class to  perform SAP data Lookup........

    Hello All,
    I want to create a generic class which is used to perorm SAP data lookup.
    I don't want to use Jco or RFC channel..
    Is there any other way to do this?
    waiting for Reply 
    thank in advance.
    - AKSHAY.

    Hi,
    use RFC channel
    you can wrap it up like this:
    /people/morten.wittrock/blog/2006/03/30/wrapping-your-mapping-lookup-api-code-in-easy-to-use-java-classes
    why do you want to create something diffucult to maintin and non standard if
    you can use the RFC API ?
    Regards,
    michal
    <a href="/people/michal.krawczyk2/blog/2005/06/28/xipi-faq-frequently-asked-questions"><b>XI / PI FAQ - Frequently Asked Questions</b></a>

Maybe you are looking for