Generic class literal?

I thought it would be useful if the class literal could return a generic class. For
e.g. something like this
Class<HashMap<Long,Long>> c = HashMap.class;
Obviously the above will not work by typecasting or templating the RHS. A
work around could be something like
HashMap<Long,Long> h = new HashMap<Long,Long> ();
Class<HashMap<Long,Long>> c = (HashMap<Long,Long>)h.getClass();
Are there any other better work arounds?

Hmmm, I was thinking of passing a generic Class to
the method so that I could use reflection to
instantiate the class (instead of new HashMap<K,
V>()). That way, the method would work not just for
HashMap but for anything implementing Map. For e.g. I
also use EnumMap simillarly.Okay, now I see where you're going with this. I don't see any reason the following wouldn't work if the client uses it correctly. You would need to document clearly the class must either be generic or implement the parameterized types specified and it must have a no-argument constructor.
    <K, V> Map<K, V> putIfMissing(final String key,
                                  final Map<String, Map<K, V>> h,
                                  final Class<? extends Map> clazz)
            throws IllegalAccessException, InstantiationException {
        Map<K, V> value = h.get(key);
        if (value == null) {
            // Unchecked assignment.  Will be fine if the class passed is a
            // generic Map or if it implements Map<K, V> with the same types.
            value = clazz.newInstance();
            h.put(key, value);
        return value;
    }You'll have to be very careful to document everything that could go wrong with this. Even then I'm not sure there's not a gotcha in there somewhere. A perhaps more object-oriented and safer solution, though more verbose, would be for the client to pass the mechanism for creating the map.
    interface MapFactory<K, V> {
        Map<K, V> createMap();
    <K, V> Map<K, V> putIfMissing(final String key,
                                  final Map<String, Map<K, V>> h,
                                  final MapFactory<K, V> factory) {
        Map<K, V> value = h.get(key);
        if (value == null) {
            value = factory.createMap();
            h.put(key, value);
        return value;
    }

Similar Messages

  • 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();
    }

  • 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

  • Class literal in CLDC 1.0 vs. CLD C1.1

    I'm using the NetBeans IDE v3.5 with the J2MEWTK 2.1 module to develop a CLDC1.0 MIDlet.
    I've found that if I use a class literal in my code (e.g. TextBox.class) the compiler gives the very informative error: "Errors compiling TestClassLiteralMidlet."
    I've also found that if I change the CLDC version of the project from CLDC 1.0 to CLDC 1.1 it works properly.
    Finally, I've found that if I compile the MIDlet for CLDC1.1 then try to run it on the "DefaultColorPhone [WTK 1.0.4]" the emulator gives the error:
    ALERT: Unable to load class java/lang/NoClassDefFoundError
    So, I assume the problem is that using a class literal is somehow generating code that requires the java.lang.NoClassDefFoundError.
    Any idea's how to get the compiler to compile this code properly for CLDC 1.0 phones?
    Thanks,
    Dave
    Entire MIDlet file:
    * TestClassLiteralMIDlet.java
    * Created on June 10, 2004, 2:03 PM
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    * An example MIDlet with simple "Hello" text and an Exit command.
    * Refer to the startApp, pauseApp, and destroyApp
    * methods so see how each handles the requested transition.
    * @version
    public class TestClassLiteralMIDlet extends MIDlet implements CommandListener {
    private Command exitCommand; // The exit command
    private Display display; // The display for this MIDlet
    public TestClassLiteralMIDlet() {
    display = Display.getDisplay(this);
    exitCommand = new Command("Exit", Command.SCREEN, 2);
    * Start up the Hello MIDlet by creating the TextBox and associating
    * the exit command and listener.
    public void startApp() {
    String s = "This is a " + TextBox.class.getName();
    TextBox t = new TextBox("Hello MIDlet", s, 256, 0);
    t.addCommand(exitCommand);
    t.setCommandListener(this);
    display.setCurrent(t);
    * Pause is a no-op since there are no background activities or
    * record stores that need to be closed.
    public void pauseApp() {
    * Destroy must cleanup everything not handled by the garbage collector.
    * In this case there is nothing to cleanup.
    public void destroyApp(boolean unconditional) {
    * Respond to commands, including exit
    * On the exit command, cleanup and notify that the MIDlet has been destroyed.
    public void commandAction(Command c, Displayable s) {
    if (c == exitCommand) {
    destroyApp(false);
    notifyDestroyed();

    Actually, neither of your answers is correct.
    TextBox.getClass() doesn't work because getClass() is not a static method (in my actual code, I don't want to instantiate a class just to get the Class reference).
    TextBox.class is a proper class literal and should work (and does with CLDC1.1).
    I just need help working around an apparent bug in NetBeans, JDK1.4, or WTK2.1 where it doesn't work when compiling for CLDC1.1.

  • Array of generic class

    Hi.
    i have to create an array of generic class
    ex: GenericClass<E> [ ] x = new GenericClass<E>[ y ]
    is it possible?
    i can create GenericClass<E> [ ] x; but i can't initiate it in this way..
    Someone know how i can do it?

    crosspost
    http://forum.java.sun.com/thread.jspa?threadID=746524&messageID=4272614#4272614

  • 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

  • How to get the parameter name of a generic class?

    Is it possible to get the name of generic class parameter type without having an instance of that type?
    e.g.
    class MyClass<T> {
      public MyClass() {
      // get the name here
    }

    I need to get a string containing "Object" (or "java.lang.Object") if the class would be used like this:
    MyClass<Object> mc = new MyClass<Object>()

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

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

  • Question about typecast to more generic Class

    I have controls refnum and pages refnum and I want to know which way is better:  
    1) let LabVIEW doing the job
    or 2) use "typecast to more generic Class". 
    In both case the VI works properly. 
    Thanks
    Jean-Marc
    Jean-Marc
    LV2009 and LV2013
    Free PDF Report with iTextSharp
    Solved!
    Go to Solution.
    Attachments:
    Test LV86.zip ‏153 KB

    Thanks for your reply Ben.
    I need the controls refnum in the visible part of the pane (for the translation english to french and french to english ).
    Jean-Marc
    Jean-Marc
    LV2009 and LV2013
    Free PDF Report with iTextSharp
    Attachments:
    Translation LV86.zip ‏235 KB

  • Accessing enum members from enum Class literal

    I'm using enums to provide a configuration framework. They work well, but I've hit a problem. This may be a bad use-case or just end up as a limitation of the enum support.
    In a nutshell I want to return the enum container type from a method and allow clients to access the members of that enum directly. For example:
    interface Widget
      Class<?> getColours();
    class MyWidget implements Widget
      enum COLOUR { RED, GREEN, BLUE };
      public Class<COLOUR> getColours() { return COLOUR.class;}
    // client
    MyWidget w = new MyWidget();
    w.setColour( w.getColours().BLUE ); // compile error!Of course, this gives a compile error as getColours() returned a class literal which doesn't have the field BLUE. However it seems like there should be a way to do this as all the information is there (the class literal has the necessary type information and can see the type is an enum). I've see Class#getEnumConstants() but this defeats the point by using an id or key to the enum rather than the enum member. Perhaps something like Class#asEnum():
    COLOUR b = w.getColours().asEnum().BLUE;I currently solve this by using naming conventions. Each widget implementer is required (by the framework) to provide an enum with the name 'COLOUR' that provides the colours it supports. However I'd prefer to have this on the interface to remind implementers to expose these configuration options.
    One other workaround is to create a custom container that holds a reference to each enum field ... but its not pretty:
    class MyWidget implements Widget
      public static class COLOURS
        private static COLOURS instance = new COLOURS();
        private COLOURS() {}
        public COLOUR RED = COLOR.RED;
        public COLOUR BLUE = COLOR.BLUE;   
        public COLOUR GREE = COLOR.GREEN;
        enum COLOUR { RED, GREEN, BLUE };
      public COLOURS getColours() { return COLOURS.instance;}
    // client
    MyWidget w = new MyWidget();
    w.setColour( w.getColours().BLUE ); // OKHas anyone hit this before and found a better solution? Is there something I've missed? If not does this seem like a reasonable request for improvement?

    I suspect you're better off using the static values() or valueOf(String) methods on the enum you create.
    So you could do
    Colour c = Colour.valueOf("BLUE");or even
    Color particularColour = null;
    for(Colour c : Colour.values()) {
        if (c.isApplicable(someCriteria)) {
            particularColour = c;
            break;
    }assuming you created a method isApplicable in the Colour enum. All I'm trying to suggest in this latter example is that selection of an enum value might be better delegated to the enum than performed by the caller.

  • Support for generic classes

    hi,
    i m using creator 2 update 1, it does not support generic classes.
    it says use source 1.5 for generic classes.
    please tell me how to solve this problem
    thank you

    Well, not necessarily true... Most of the latest graphics cards work off of a common core, which is named depending on its maximum tested performance and on how many pipelines passed quality checks.
    Thus a 7300 is fundementally identical to a 7800, except that it uses fewer fragment/vertex pipelines and is clocked lower. This is done either artificially by disabling parts of the GPU, or if when they fail quality control.
    Either way, the drivers are the same, and have been unified for a long time for the entire product line. In fact if you look at the drivers for the card in yoru computer you will see they are more then likely for a different chipset. My MBP claims the drivers are for a X1000, even though the card is a X1600.

  • 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

Maybe you are looking for

  • How to get the Open qty. in JIT Schedule in VA33 txn.

    How to get the Open qty. in JIT Schedule in VA33 txn. The F1 Helps says Structure VBEPD field name is OLFMNG.

  • ITunes 10.6.1 problems

    Hi,      I'm running 10.7.3 Lion on a 2011 Mac Mini. Using as a media centre mostly. iTunes is causing no end of problems. It will stop all output (using hdmi output) randomly. Looking at the monitor iTunes appears to be playing normally. A side effe

  • Is the map updated with IOS 6.0.1

    i mad mistake when i install IOS 6 because i had a map problem,anyone has installed the new version IOS 6.0.1 can informe me if it has any update for the map or no.

  • Batch program with COR1

    Hi : I want to create a batch program using call transaction for process order COR1. I need an example for this, by creating a recording " shbd " using COR1. Thanks. Rag

  • Customizing link to table T158

    Dear friends , Does anyone could help me to find the transaction code that update table T158- Transaction Control: Inventory Management ? We need to understand if is possible to inclue one more tcode there. best regard, Ale