Need ideas - pattern using generics

Recently I tried to implement sth. simillar to ActionListeners pattern in Swing.
(this is common pattern for handling actions etc.)
... I encountered few problems (compiler errors, warnings).
I prepared sample code that highlights it.
---- Main.java ----
package genericstest;
import java.util.ArrayList;
class Event {
public String toString() {
return "base event";
interface GenericListener<T extends Event> {
public void doAction(T ev);
class MyEvent extends Event {
public String toString() {
return "my event";
class MyListener implements GenericListener<MyEvent> {
//this method implements interface method
//- as far as I know it is legal according to spec
//and sth I really like in java generics
public void doAction( MyEvent e) {
System.out.println("in my listener:"+e.toString());
public class Main {
public static void main(String[] args) {
new Main().run();
private void run() {
Event me = new MyEvent();
//solution that I chosen - with one cast - works, compiles w/o warnings
ArrayList<GenericListener<Event> > listns =
new ArrayList< GenericListener<Event> >();
//here is the cast I would like to avoid
GenericListener<Event> el = (GenericListener<Event>) new MyListener();
listns.add( el);
for (GenericListener<Event> l : listns)
l.doAction( me );
//my: first solution - compiler gives warning [unchecked]
//use -Xlint:unchecked flag
/*ArrayList<GenericListener > listns = new ArrayList<GenericListener >();
listns.add( new MyListener());
for (GenericListener l : listns) {
l.doAction( me );//here is warning
//one of not compiling solutions - I tried to go with "? extends" and "? super"
//but got no sensible results
ArrayList<GenericListener<? extends Event> > listns = new ArrayList<GenericListener<? extends Event> >();
listns.add( new MyListener());
for (GenericListener<? extends Event> l : listns) {
l.doAction( me //this produces compiler error
---- End of file -----
Code above works (as expected) but contains one small cast that I would like to avoid.
I was trying to rewrite it but never got anything satysfying (see in sample).
After reading topic:
http://forum.java.sun.com/thread.jsp?thread=512445&forum=316&message=2541231
I understood all errors, warnings...problem... but finally I realised that "probably" I am not able to write my code without using casts (or having warnings). (The problem is that in one place I need both contrvariance and covariance (if aI am calling things correctly - adding to generic collection and retriving from same collection) ).
So the question is:
Does anybody have any idea how to rewrite code above ? I am particullary interested in using
this new small language feature that allows me to write my own ActionListeners without using casts (see MyListener).

First, it is good to understand what you want to do, otherwise there's no chance to convience compiler that you are doing right :)
From this code: Event me = new MyEvent(); It is obvious that you want to deliver MyEvent to some listeners. If you are delivering MyEvent, then you should have a list of MyEvent listeners (listeners for any other Event are not good -- they cannot process MyEvent anyway, because they expect arguments of different type). So, why in your code you are trying to declare a List<GenericListener<Event>>? If you want to have a list of MyEvent listeners, then you shall have List<GenericListener<MyEvent>>.

Similar Messages

  • Hi All ,need ideas on using oracle apex maps...

    Hi All,
    I need a map on country like trinidad and Tobago and jamaica together how do I accomplish that...using the current oracle apex..
    I couldnt find country tobaga and Trinidad listed there
    Thanks any guidance shall be appreciated..
    Paul j

    Hi Paul,
    There actually isn't a country map for Jamaica or Trinidad and Tobago in the suite of AnyChart maps that we integrate into Application Express. Your easiest option is to use either the World, Americas or North America map - either of these will allow you to represent Jamaica and Trinidad & Tobago on a map, and associate data with it. I've used the Americas map as an example here: http://apex.oracle.com/pls/apex/f?p=36648:89.
    I appreciate that this isn't ideal if you wish to represent these locations on their respective country maps, but it might be a possible workaround for you. Alternatively, you would need to source your own Shapefiles for these countries, and use the AnyChart Flash Map Converter utility - http://anychart.com/products/anymap/converter/ - to convert your Shapefile into a .amap file. That .amap file would then need to be incorporated in your APEX /images directory, and its information would then need to be referenced in your map SQL query in order to associate data with the new maps. For further information on the Converter utility, or indeed on the AnyChart maps, please refer to the AnyChart site: http://anychart.com/products/anymap/docs/.
    Regards,
    Hilary

  • Can not replicate Java 1.4 pattern using Java 5 generics

    I am trying to migrate some 1.4 code to Java 5. The code below captures the essence of what I am trying to do. Trouble is I get the following error
    Name clash : The method readAll(List<XyzData>) of type Generics has the same erasure as readAll(List<Data>) of type Generics.DAO but does not override it
    I sort of understand why it doesn't compile however I am unsure how to fix it, or even if I can use generics in this instance and if I can what is the syntax?
        public abstract class DAO
            public abstract void readAll(List<Data> data);
        public class XyxDAO
        extends DAO
            public void readAll(List<XyzData> xyzData)
        }I certainly need to do some more reading about this generics stuff but any help now would be much appreciated.

    Without a bit more background, it's difficult to be precise, but I would imagine you want something like this (untested):
    // Should this be an interface?
    public abstract class DAO<T extends Data> {
      public abstract void readAll(List<T> data);
    public class MyDAO extends DAO<MyData> {
      public void readAll(List<MyData> myData) {
    }

  • Factory Patterns with Generics

    I am trying to combine the good old factory pattern with generics and could use some advice.
    I have the following
    //Base class from which all my things extend
    public abstract class Thing {
    //one kind of thing
    public class ThingOne extends Thing {
    //another kind of thing
    public class ThingTwo extends Thing {
    //interface for my factory
    public interface ThingFactory<T> {
    public T create(long id);
    //a factory for thingones
    public class ThingOneFactory<T> implements ThingFactory<T> {
    public T create(long id) {
    return (T) new ThingOne();
    public class TestClass{
    public <T extends Thing> T getThing(ThingFactory<T> tf){
    //do a bunch of generic stuff to figure out id to call create
    ThingFactory<T> instance = tf;
    return (T) instance.create(Long id);
    }My calling code would know what kind of thing it needs but necessarily the things id. Which can be computed in a generic way.
    TestClass gt = new TestClass();
    gt.getThing(new ThingOneFactory<ThingOne>());This all seems to work properly but I am getting "Type safety: Unchecked cast from ThingOne to T" in my ThingOneFactory
    My T's will always extend Thing, what am I missing? Is there a better way to do this?
    Edited by: nedry on Dec 29, 2009 5:39 PM

    I thought of that after I posted. But that just moves my unsafe cast warning into TestClass.Why?
    return (T) instance.create(Long id);That can't have ever compiled. What is the exact code? And why did you have to cast (what was the warning/error)?

  • Must we uses generics always

    Hi,
    We are using eclipse as a tool with java 1.5 development.
    But the tool issues warning for the below code.
    ArrayList list = new ArrayList();The problem is it is expecting
    ArrayList[u]<E>[/u]  list = new ArrayList();Is it wrong to ignore using the "Generics".
    Or does it in anyway make the code non-compliant with 1.5.
    I dont feel the need to use Generics,
    so cant i ignore it ?
    Any thoughts on this matter are appreciated.
    Regards,
    Shailesh

    Is this the Java Kindergarden?In my experience, mostly yes.
    Of course, one can use Java the raw fashion. The fact that you can doesn't make it a good idea. Generics are one of the most beneficial new feature in Java.
    Generics
    "only" provide some compile-time type safety in many
    situations, but not all of them. Often enough, you
    will work with bound types or even wildcards, which
    not helps much.In most cases compile-time is the best time to be as safe as possible.
    It surely is possible to safely develop applications
    with less or no types (e.g. dynamic typing, cf. Ruby,
    Smalltalk, Python etc.).Of course it is, it's also easier to make mistakes which burn you at runtime.
    It all depends on who will
    write the code, who will maintain the code, and how
    experienced the developers are.In which case I find it best to assume the worst.
    Comparisons to assembler or register manipulations
    are quite off. Types alone do not guarantee a stable
    or maintainable application.But they do help.

  • Need ideas and stuff for a new laptop or netbook.

     Need ideas. I'm lookin to buy a new laptop soon. Next couple months. I want something that runs good, runs fast, doesn't have a lot of junk installed on it and something below $700 dollars (may pay more...just depends). Any brands that are good? I thought maybe getting a netbook because I really just need some small storage and an awesome internet. Would a netbook be good for that?  I use verizon wireless on my laptop right now but I'm going to switch to AT&T soon.

    In todays world of Net Books, 250 GB and 2 gb configurations are becoming standard. However, a majority of the Net Books out there still have the standard 1gb and 160gb hard drive configurations. You can upgrade the hard drives and memory in the newer Acer Netbooks now because of the redesign the did to the casing. The 8.9 inch net books Acer came out with could not allow the hardware upgrades because of their initial proprietary casing design. But with hacking and warranty voiding someone did it.
    The bare minimum price you can expect to pay for a Net Book is $299 on average for the majority specs I posted. For better specs you will pay more for them.
    Please always buy an optical drive with a Netbook or purchase a $399 laptop in the end for better flexibility.
    *******DISCLAIMER********
    I am not an employee of BBY in any shape or form. All information presented in my replies or postings is my own opinion. It is up to you , the end user to determine the ultimate validity of any information presented on these forums.

  • How to use Generic Object Services(GOS) for each table control record.

    Dear Expert,
                       I am using generic object services for document attachment but i am facing a problem while attaching document to a table control row. my requirement is to attach separate document for each and every row of table control but  i am unable to attach document row wise of the table control.for each row GOS should display corresponding attached document not all the attached document.
    Thanks in Advanced
    Bhuwan Tiwari
    Edited by: BHUWAN TIWARI on Feb 8, 2011 4:16 PM
    Edited by: BHUWAN TIWARI on Feb 8, 2011 4:16 PM

    You haven't explained what object and object key you're using, nor have you provided any indication of how you implemented the GOS attachment functionality.  You need to provide more information to resolve an issue like this.

  • Attach doc from external content server- using Generic Object Service (GOS)

    Dear All,
    i have intergrated an external content server to SAP using SAP archive link. All the scanned document are there in Content server and corresponding entries are done in SAP.I can search and view document using tcode : OAAD
    Please tell me steps for "how to attach a document from external content server using Generic Object Service "
    Scenario is :  For example when we change any Master records or create a new PO, or do some financial transaction then i need to attach the supporting document which is there in my content server connected  to SAP.how do we manual attach a Document in SAP using GOS.
    Do we need to do some special configuration to use GOS .please give the steps from initial.
    Thanks
    sandeep

    Hello,
    Check your configuration of document type assignement to required business document - object type, Archivelink table, content repository in OAC3 transaction.
    Goto respective business document > Click on GOS > Create > Store business document - Here you can see defined document type with desctiption. Double click on this the assign your document to this business document. Save it.
    This will help in attaching the document to your required business document.
    To verify you can check the archivelink table or by transaction OAAD.
    Hope this will help you.
    -Thanks,
    Ajay

  • How to attach document using Generic Object Service

    Hi all,
    How can i create attachment to the parked invoice using Generic Object services? i want function modules which are used to do it.
    Actually I want to do this from the business object method. I am having word document as one of the workitem step. once i get this document I need to attach this document to the parked invoice so that users can see that document by view object list.
    Its urgent.
    thanks.

    Hello,
    Check your configuration of document type assignement to required business document - object type, Archivelink table, content repository in OAC3 transaction.
    Goto respective business document > Click on GOS > Create > Store business document - Here you can see defined document type with desctiption. Double click on this the assign your document to this business document. Save it.
    This will help in attaching the document to your required business document.
    To verify you can check the archivelink table or by transaction OAAD.
    Hope this will help you.
    -Thanks,
    Ajay

  • How to trigger a workflow using generic object services?

    Hi Experts,
    Let me know on how to trigger a workflow using generic object services.
    My requirement is to trigger the FI document reversal document using Object services.
    Any info or docs relevant to this, please share with me..
    Thanks,
    Dinesh.

    Dinesh,
    First of you need to check if the transaction has a BO (in released status) published to use the GOS.
    These are the pre-requisites for GOS
    http://help.sap.com/saphelp_46c/helpdata/en/94/aa532cddd511d289860000e8216438/content.htm
    Once done.. check that you have valid workflow linkages active for this BO.
    Now when you click on the 'start workflow' the system will show all relevant workflows for the BO to choose from and to start.

  • Poor Performance using Generic Conectivity for ODBC

    Hi my friends.
    I have a problem usign Generic Conectivity , I need update 500,000 records in MS SQL Server 2005, I'm using Generic Conectivity for ODBC. In my Oracle Database i have create a DB_LINK called TEST to redirect to MS SQL Server database.
    Oracle Database: 10.2.0.4
    MS SQL Server version: 2005
    The time for update 1,000 records in MS SQL Server using DBMS_HS_PASSTHROUGH is ten minutes. This is a poor performance.
    This is de PL/SQL
    DECLARE
    c INTEGER;
    nr INTEGER;
    CURSOR c_TEST
    IS
    SELECT "x", "y"
    FROM TEST_cab
    WHERE ROWNUM <= 1000
    ORDER BY "y";
    BEGIN
    FOR cur IN c_TEST
    LOOP
    c := DBMS_HS_PASSTHROUGH.OPEN_CURSOR@TEST;
    DBMS_HS_PASSTHROUGH.PARSE@TEST(
    c,
    'UPDATE sf_TEST_sql
    SET observation= ?
    WHERE department_id = ?
    AND employee_id = ? ');
    DBMS_HS_PASSTHROUGH.BIND_VARIABLE@TEST (c, 1, 'S');
    DBMS_HS_PASSTHROUGH.BIND_VARIABLE@TEST (c, 2, 'N');
    DBMS_HS_PASSTHROUGH.BIND_VARIABLE@TEST (c, 3, 'ELABORADO');
    DBMS_HS_PASSTHROUGH.BIND_VARIABLE@TEST (c, 4, 'PENDIENTE');
    DBMS_HS_PASSTHROUGH.BIND_VARIABLE@TEST (c, 5, cur."x");
    DBMS_HS_PASSTHROUGH.BIND_VARIABLE@TEST (c, 6, cur."y");
    nr := DBMS_HS_PASSTHROUGH.EXECUTE_NON_QUERY@TEST (c);
    DBMS_HS_PASSTHROUGH.CLOSE_CURSOR@TEST (c);
    COMMIT;
    END LOOP;
    END;
    You can help, how better the performance for update 500,000 record by record in MS SQL Server. I need advantages of use Oracle Transparent Gateway for Microsoft SQL Server.
    your's can suggest my another solution ?
    Thanks.

    Hi,
    There are no real parameters to tune the gateways. You should turn on gateway debug tracing and check the SQL that is being sent to SQL*Server to make sure is update statements and nothing else.
    If this is the case then the time taken will be down to various factors, such as network delays, processing on SQL*Server and so on.
    How long does it take to update the same number of records directly on SQL*Server without the Oracle or the gateway involved or if you use another non-Oracle client to do the same updates across a network, if a network is involved ?
    It may be possible to improve performance by changing the HS_RPC_FETCH_REBLOCKING parameter, so have a look at this note in My Oracle Support -
    Tuning Generic Connectivity And Gateways (Doc ID 230543.1)
    Regards,
    Mike

  • Why do we need IDE or tools for java card programming?

    Hi,
    I am a newbie to java card, using java card kit tools themself, we can test and burn the code into card right?
    then why do we need IDE for java card, please correct me , if i am wrong,
    Thanks in advance,
    Sri.

    Dear Sri,
    We have compiler, linker etc for every language starting of from C or C++ or Java. JDK has all the tools necessary to develop and run a Java program. Similarly Java Card Development Kit has all the tools for developing and deploying a Java Card applet. But what an IDE does is too integrate all these tools and make it easier for the JavaCard programmer to develop his applets. Just like Eclipse is used for Java applet development.And not everytime the code is burned to the card. Its only during masking code is burned to the card, i.e if u can call it burning. Masking makes an applet permanent on the card.

  • Where and when to use generics?

    I'm brushing up on Java 5.0, I'm at 'generics' - I always hated c++ templates and knew they would catch up with me sooner or later...
    I have a fairly simple question about where and how to use them, conceptually.
    Am I correct in thinking that they are primarily concerned with items contained within a class and passed to a class?
    I'm trying to find a useful bit of code to write to practice with them and I've been half tempted to re-write something that uses lots of inheritance simply because I know the code in question needed a lot of casting, but my gut feeling is that generics doesn't have an awful lot to do with inheritance and re-jigging a class that relied on inheritance to use generics is barking up the wrong tree.
    I'd really appreciate some informed comments before I go trundling off down a path that is going to end with reams of pointless code.
    Thanks,
    Steve

    IMO the most useful feature of using Generics is compile time typesafety.
    Consider the pre-1.5 code for making a LinkedList that contains strings:
    LinkedList l = new LinkedList();
    l.add("Hello world!");
    l.add(new Integer(100));    // <---- runtime exceptionInstead, you can now write the code like this:
    LinkedList<String> l = new LinkedList<String>();
    l.add("Hello world!");
    l.add(new Integer(100));    // compile time exceptionIf you accidentally put the wrong type in a Collection you will get a nice compile time exception instead of a ClassCastException at runtime.

  • variable-class using Generic Collection

    Within my TLDs I would like to use the <variable-class> attribute as much as possible for the sake of JSP authors.
    I cannot figure out how to specify that a varAttribute will be a generic collection. IE, if I want to return a set of strings, I would like to do
    <variable-class>
    java.util.set<java.lang.String>
    </variable-class>
    Of course I must escape the <,> and I tried using < and > but it was not effective.
    Is this even possible? I would appreciate any comments suggestions.

    Currently we are using a single domain account on every machine in this kiosk area. They are using just Internet Explorer and Adobe Reader. We are using Group Policy to lock down the machines. Each station is a full computer (older Dell OptiPlex) running
    Windows 7. We are looking at the possibility of removing the OptiPlex computers and replacing them with Wyse terminals. The backend would be a cluster of 3 servers running Hyper-V 2012 R2. On those would be running Windows Server 2012 R2 RDS.  We have
    tested this setup, but when creating the VDI collection there doesn't seem to be a way to use generic domain accounts. 
    Every person that uses these does not have an AD account and it looks like that would be a problem when trying to implement this.  I was just checking here to see if anyone had any ideas or had gone through a similar setup.

  • Getting information about a class using generics...

    Hi there.
    I have declared a class: "public class SomeClass<SC extends SomeClass>{/*Do something*/}".
    Can anyone tell me why a statement like "System.out.println(SC.class.getSimpleName());" within a method defined in SomeClass will not compile? Is there some other way to achieve what I want?

    YoungWinston wrote:
    Owen Thomas wrote:
    Well then, it would be great to be able to key a switch that tells the compiler one isn't working with "legacy code", if this might allow generics to reach a hitherto untapped potential.I don't see how, since not everybody is going to need (or want) such a switch. It also sounds like a recipe for disaster. Should we add such a switch for every enhancement that might have backwards-compatibility problems?Isn't that what the "deprecated" feature is for? Sure, there'll be backwards compatibility issues for a while, but after a few years, with management, things should settle as code is moved from pre to post "super-generics".
    Much of the Java core, and many third-party libraries might have to be re-written in that circumstance... economic stimulus.How could the Java core have been re-written if it requires use of a "not backwards-compatible" flag?i have not reason to believe that code compiled under a super-generics switch need not be backwards-compatible. One may have to simply exercise care in its use.
    I didn't want to bore you with trivia, and I didn't want you to frustrate me with more quips (well-meant though I'm sure they are) about how to write code. ;-)In which case I can only assume that you're using generics for something that probably, more correctly, requires reflection. Have you looked at the relevant parts of Class, as I suggested?No, but as you are impressing on me to have a look, I could do no wrong to have a sniff around. However, with no specific motivation in the current context, I don't think anything will catch my eye. The current need isn't great enough.

Maybe you are looking for

  • Oracle 10.1.3.

    Hi, I recently installed oracle app server 10.1.3 and following the instructions Reconfiguring Application Server Instances I tried to make it so that my 10.1.3 app server can use SSO with my 10.1.2 infrastructure. I deployed an application on 10.1.3

  • Function 'HR_READ_INFOTYPE'  not fetching any records in rfc

    Hi All,    We have created a custom info type 9110 , we have a wrapper RFC build around the function 'HR_READ_INFOTYPE' to read the data from it as we have a separate web dynpro ECC 6.0 system and a 4.7 back end system.    The rfc is working correctl

  • Can Markers (or anything else) automatically change the patch?

    I've been looking all over to try and figure out how to have MainStage automatically change to the next patch when a new Marker comes up on the backing track through PlayBack. Basically, when i'm playing to a backing track, i sometimes play the pads

  • COLLECTION in PROCEDURE

    how I pass a collection data through OUT parameter in PROCEDURE SQL>create or replace type mytype as object(eid number,empname varchar2(20)); SQL> create or replace type mytype_nt as table of mytype; SQL> ed Wrote file afiedt.buf 1 create or replace

  • Distinguish between TABLES Paramters

    Hello! For Example is the FM below given. How can you distinguish between TABLES Paramters ? starting with X_ are those in which data is passed starting with E_ are exporting tables, which get filled within the F/M. starting with  I_ ????????????????