Generic cursor type // generic datatype

Hi,
I would like to dynamically declare a cursor in my procedure and retrieve rows from it for firing insert / update statements on another table. The procedure should take a table_name in VARCHAR2 and use it to declare a cursor like:
procedure thisProcedure (table_name in VARCHAR2) is
cursor thisCursor is select * from <table_name>;
thisRow thisCursor%ROWTYPE;
begin
loop
fetch thisCursor into thisRow
-- exit when empty
-- do sth. with this record (insert or update on another table depending on data in thisRow)
end loop;
end thisProcedure;
I have been around in several forums and have got as far as declaring a weak cursor variable (one declared without return clause) and then opening this cursor with dynamic SQL. However, the moment I want to fetch a row of that cursor into a record, I would fail as weak cursor variables do not know their ROWTYPE. So in that case, I would have the cursor correct, but I would not have the corresponding - generically and dynamically declared - datatype:
procedure thisProcedure (table_name in VARCHAR2) is
type thisCursorType is ref cursor;
thisCursor thisCursorType;
thisRow <table_name>%ROWTYPE;????
begin
open thisCursor for 'my dynamic SQL';
loop
fetch thisCursor into WHAT???????
-- exit when empty
-- do sth. with this record (insert or update on another table depending on data in thisRow)
end loop;
end thisProcedure;
Anybody know a solution or a workaround? Anything?
Cheers
Sebastian

Maybe you can use object types and ANYDATA/ANYTYPE types. For example:
CREATE TYPE dept_obj_type AS OBJECT (
   deptno NUMBER (2),
   dname  VARCHAR2 (20)
CREATE TABLE dept_obj_table OF dept_obj_type
CREATE TYPE emp_obj_type AS OBJECT (
   empno  NUMBER (4),
   ename  VARCHAR2 (20),
   deptno NUMBER (2)
CREATE TABLE emp_obj_table OF emp_obj_type
-- procedure inserts a "generic object type" variable
CREATE OR REPLACE PROCEDURE gen_insert1 (
   p_table   VARCHAR2,
   p_anydata ANYDATA)
IS
   l_statement VARCHAR2 (32000);
BEGIN
   l_statement :=
   '  DECLARE' ||
   '     l_anydata ANYDATA := :p_anydata;' ||
   '     l_object ' || p_anydata.GetTypeName || ';' ||
   '     l_result_code PLS_INTEGER;' ||
   '  BEGIN ' ||
   '     l_result_code := l_anydata.GetObject (l_object);' ||
   '     INSERT INTO ' || p_table || ' VALUES (l_object);' ||
   '  END;';
   EXECUTE IMMEDIATE l_statement USING IN p_anydata;
END;
-- unnamed PL/SQL block for testing
DECLARE
   l_dept dept_obj_type;
   l_emp  emp_obj_type;
BEGIN
   -- creates objects
   l_dept := dept_obj_type (10, 'dept 10');
   l_emp  := emp_obj_type (2000, 'emp 2000', 10);
   -- inserts objects
   gen_insert1 (
      p_table   => 'dept_obj_table',
      p_anydata => ANYDATA.ConvertObject (l_dept));
   gen_insert1 (
      p_table   => 'emp_obj_table',
      p_anydata => ANYDATA.ConvertObject (l_emp));
END;
/For (very complicated) relational version see
Inserting a "Generic Record Type" Using ANYDATA/ANYTYPE Types
http://www.quest-pipelines.com/pipelines/plsql/tips04.htm#MARCH
Regards,
Zlatko Sirotic

Similar Messages

  • Generic cursors and generic result sets - How to?

    Hi all,
    I'm currently developing some kind of table export util. All it should do is to take a list of table names, determine the table structure (aka fields), fetch all data from this table and store a flat textfile containing all table data as ready-to-use INSERT statements.
    Please do not tell me that I could use DataPump or imp/exp, I know this but in this specific project this is not possible. I simply need one textfile per Table, that's it.
    So far my approach is the following:
    - Developed a package which contains a hard-coded list of tables as "TABLE OF VARCHAR2".
    - One procedure inside this package determines the list of fields for every passed tablename and their corresponding fieldtypes and generates a SELECT and INSERT query.
    - Another procedure will get the created SELECT query (which is valid, I've tested this) and performs a "OPEN <generic_cursor> FOR <select_query>";
    And here is also my problem. After "OPEN" the generic cursor I need a record to fetch the data row into. However as the list of tables is dynamic, so must be the records where to fetch into. I did not find any possible way of dynamically creating a record for the "FETCH INTO" statement. So far the only solution I've found was to hardcode the results of the tables and use IF/ELSE or CASE logic inside the data retrival procedure to fetch always into the right record:
    PROCEDURE DUMP_TABLES(P_TABLENAME VARCHAR2, P_SELECT VARCHAR2)
    G_CV genericcurtyp;
    T_MC_USERS MC_USERS%ROWTYPE;
    T_CDALBUM CDALBUM%ROWTYPE;
    BEGIN
    OPEN G_CV FOR P_SELECT;
    LOOP
    IF P_TABLENAME = 'MC_USERS' THEN
    FETCH G_CV INTO T_MC_USERS;
    ELSE
    FETCH G_CV INTO T_CDALBUM;
    END IF;
    EXIT WHEN G_CV%NOTFOUND;
    END LOOP;
    END;
    What I really would like to use is something like this:
    PROCEDURE DUMP_TABLES(P_TABLENAME VARCHAR2, P_SELECT VARCHAR2)
    G_CV genericcurtyp;
    TYPNAME VARCHAR2(32):='T_'||P_TABLENAME;
    MYRES TYPNAME%ROWTYPE;
    BEGIN
    OPEN G_CV FOR P_SELECT;
    LOOP
    FETCH G_CV INTO MYRES;
    EXIT WHEN G_CV%NOTFOUND;
    -- Do something with the row data in MYRES
    END LOOP;
    CLOSE G_CV;
    END;
    Of course I could hard-code everything, however I would like to keep the possibility to extend the list of tables simply by adding another entry to my list of tablenames without having to add additional code whenever the table list changes.
    I've tried also the "FOR i IN (<SELECT>)", however this won't accept a variable for the <SELECT>.
    Maybe someone here as an idea how to solve this problem without having to hard-code the required result sets of all affected tables? Or maybe I'm simply going the wrong way and someone could show me the right one?
    Any help would be appreciated.
    Best regards,
    Sascha

    You could use DBMS_SQL instead. DBMS_SQL provides DESCRIBE procedure so you can get count and datatypes of select list elements. If you are on 11g you can convert ref cursor to DBMS_SQL cursor or vice versa. But I would use a different solution. First of all, what are you creating "export" for? If you are planning to use it to load data into another Oracle database I'd simply use external tables. If you really need CSV, I'd use DBMS_SCHEDULER and run SQL*Plus task spooling output to a file.
    SY.

  • Cluster resource 'Analysis Services' of type 'Generic Service' in clustered role 'SQL Server' failed.

    Windows Server 2012 R2
    SQL Server 2012
    After a recent cluster failover from node 1 to node 2, the Analysis Services role is in a failed state, with the service stopped. When attempting to start the service, there are two error messages captured in Failover Cluster Manager:
    Log Name:      System
    Source:        Microsoft-Windows-FailoverClustering
    Date:          4/10/2014 11:48:49 AM
    Event ID:      1042
    Task Category: Generic Service Resource
    Level:         Error
    Keywords:      
    User:          SYSTEM
    Computer:      HQ-HASQL-1.sbgnet.int
    Description:
    Generic service 'Analysis Services (HASQL)' failed with error '1067'. Please examine the application event log.
    Event Xml:
    <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
      <System>
        <Provider Name="Microsoft-Windows-FailoverClustering" Guid="{BAF908EA-3421-4CA9-9B84-6689B8C6F85F}" />
        <EventID>1042</EventID>
        <Version>0</Version>
        <Level>2</Level>
        <Task>16</Task>
        <Opcode>0</Opcode>
        <Keywords>0x8000000000000000</Keywords>
        <TimeCreated SystemTime="2014-04-10T15:48:49.752168200Z" />
        <EventRecordID>26212</EventRecordID>
        <Correlation />
        <Execution ProcessID="9036" ThreadID="14748" />
        <Channel>System</Channel>
        <Computer>HQ-HASQL-1.sbgnet.int</Computer>
        <Security UserID="S-1-5-18" />
      </System>
      <EventData>
        <Data Name="ResourceName">Analysis Services (HASQL)</Data>
        <Data Name="Status">1067</Data>
      </EventData>
    </Event>
    Log Name:      System
    Source:        Microsoft-Windows-FailoverClustering
    Date:          4/10/2014 11:48:49 AM
    Event ID:      1069
    Task Category: Resource Control Manager
    Level:         Error
    Keywords:      
    User:          SYSTEM
    Computer:      HQ-HASQL-1.sbgnet.int
    Description:
    Cluster resource 'Analysis Services (HASQL)' of type 'Generic Service' in clustered role 'SQL Server (HASQL)' failed.
    Based on the failure policies for the resource and role, the cluster service may try to bring the resource online on this node or move the group to another node of the cluster and then restart it.  Check the resource and group state using Failover Cluster
    Manager or the Get-ClusterResource Windows PowerShell cmdlet.
    Event Xml:
    <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
      <System>
        <Provider Name="Microsoft-Windows-FailoverClustering" Guid="{BAF908EA-3421-4CA9-9B84-6689B8C6F85F}" />
        <EventID>1069</EventID>
        <Version>1</Version>
        <Level>2</Level>
        <Task>3</Task>
        <Opcode>0</Opcode>
        <Keywords>0x8000000000000000</Keywords>
        <TimeCreated SystemTime="2014-04-10T15:48:49.752168200Z" />
        <EventRecordID>26213</EventRecordID>
        <Correlation />
        <Execution ProcessID="6464" ThreadID="9076" />
        <Channel>System</Channel>
        <Computer>HQ-HASQL-1.sbgnet.int</Computer>
        <Security UserID="S-1-5-18" />
      </System>
      <EventData>
        <Data Name="ResourceName">Analysis Services (HASQL)</Data>
        <Data Name="ResourceGroup">SQL Server (HASQL)</Data>
        <Data Name="ResTypeDll">Generic Service</Data>
      </EventData>
    </Event>
    With just these generic error messages being present, this has been difficult to diagnose. Some research has yielded possible resolutions of the Event Viewer log being full, .NET corruption, missing registry entries, but none of those seem to be the issue
    (Event Viewer logs cleared, Analysis services is working on the same physical servers in a different cluster, and the registry entries was only a supported issue for SQL Server 2008 and 2008 R2).
    Any help would be greatly appreciated.

    Bring up Configuration Manager, look at binary path for SSAS.  Make sure BOTH folders exist.  Sometimes with failovers mappings get screwed up.

  • Loading custom Generic Loader type extracts broken after patch 7616161

    Before applying 7616161, we could perform full ETL operations within iSetup using custom apis for a seeded .lct file. After applying this patch, extracts still work using the same custom apis, but loads fail with the following error:
    Validating Primary Extract...
    Parsing driver.xml
    Time taken to parse the Driver file and construct setup objects:25 milliseconds
    Sorting Apis based on their dependency...
    null
    java.lang.NullPointerException
         at oracle.apps.az.r12.api.APISorter.sortBySeqNum(APISorter.java:599)
         at oracle.apps.az.r12.loader.cpserver.APILoader.groupApis(APILoader.java:449)
         at oracle.apps.az.r12.loader.cpserver.APILoader.loadAPIs(APILoader.java:226)
         at oracle.apps.az.r12.loader.cpserver.APILoader.callAPIs(APILoader.java:141)
         at oracle.apps.az.r12.loader.cpserver.LoaderContextImpl.load(LoaderContextImpl.java:66)
         at oracle.apps.az.r12.loader.cpserver.LoaderCp.runProgram(LoaderCp.java:65)
         at oracle.apps.fnd.cp.request.Run.main(Run.java:157)
    Concurrent program completed.
    Any help would be most appreciated.

    In an instance that was cloned with 12.0.6 after applying 7616161, then upgrading the instance to 12.1.1, still getting this problem, specifically the nullpointerexception error in the APISorter class. Will the patch 8871713 work under this upgraded instance as well? Or do I need different code to patch up iSetup to get the Generic Loader type extensions working in 12.1.1?

  • How to define a generic structured type (deep structure) w/o LIKE

    Hi,
    I have been trying to define a generic structured type that would include a component (field) of type "table type".
    Look at my type [ty_compatibilite].  It is the structured type that needs to have a component called "mobile" which needs to be an internal table.  I have tried to create a genereic table type called tt_mobile (based on ty_mobile) but that did not work. I have not been able to avoid using the LIKE command to make it work.
    Any suggestions on how I could define my component "mobile" without using a "LIKE"... ?
    Here is my code:
    TYPES: BEGIN OF ty_mobile,
              ref_mob_sfr    TYPE zmobil,
              ref_mrq_sfr    TYPE zmarq,
              type_compat    TYPE zsea_comp_type,
           END OF ty_mobile.
    TYPES: tt_mobile TYPE STANDARD TABLE OF ty_mobile.
    DATA: lit_mobiles TYPE STANDARD TABLE OF ty_mobile.
    TYPES : BEGIN OF ty_compatibilite,
              cod_ean        TYPE ean11,
              lib_art        TYPE maktx,
              compat_all_mrq TYPE zsea_comp_gen,
    *          mobile        TYPE tt_mobile,
              mobile         LIKE lit_mobiles,
            END OF ty_compatibilite.
    TYPES : tt_compatibilite   TYPE STANDARD TABLE OF ty_compatibilite.

    define key or use default one:
    TYPES: tt_mobile TYPE STANDARD TABLE OF ty_mobile with DEFAULT KEY.
    If you don't specify key the type is treated as generic

  • Generic cursor

    Hello everyone,
    I'm creating a package with lots of procedures with them. This is small snippet from the package
    CREATE OR REPLACE PACKAGE mridpack AS
    CURSOR c1 IS SELECT * FROM cases;
    TYPE empCur IS REF CURSOR RETURN c1%ROWTYPE;
    PROCEDURE GetEmpData(EmpCursor IN OUT empCur);
    END;
    CREATE OR REPLACE PACKAGE BODY mridpack AS
    PROCEDURE GetEmpData
    EmpCursor IN OUT empCur
    IS
    BEGIN
    OPEN EmpCursor FOR SELECT * FROM cases WHERE rownum < 10;
    END;
    END;
    Each of procedure return a ref cursor which i use to access the data. However each of the SQL snippets inside each of the procedures are different. Would i have a declare different cursor types for each procedure in the package specification or is there a way i can use common cursor type?

    you can declare a single cursor variable by using a weak ref cursor with the SYS_REFCURSOR type. this way, you can use the same cursor variable for your various SQL statments.

  • How to deal with delete record in generic delta of generic datasource

    Hi,
       Anyone can give me suggestion about the delete record in generic delta  of generic data. I need extract data with a generic datasource and hope deleted record in datasource also can be "delete" in next delta extraction. I do a test with generic delta. It seem that the delete record can not be updated in ODS. but updated record can be updated in next delta extraction.
    How dose BW generic delta deal with the deleted record with generic delta mechanisim? Or how can I use generic delta mechanisim to realize that BW "delete" the deleted record of source system in ODS with delta extraction?
    Thanks in advance!
    Billy

    Delete is not supported in delta mechanism of generic delta extractor. You will need to add a workaround for that.
    - Capture the deleted records somewhere (maybe enhance the txn deleting the record so the key is written to a Z table). Take these records to BW and manipulate the recordmode to affect deletion of corresponding record from ODS.
    - If your generic delta is based on FM, and if the 'delete' is captured in change document tables, add the logic to check change document tables whether any records are deleted, and if yes, send those to BW with appropriate recordmode to achieve deletion.

  • WEAK REF CURSOR type

    This is the first time I have a need at work to use a REF CURSOR type of the weak variety. After reading documentation
    in SF's 'bible' Oracle PL/SQL Programming, I did everything right. Here's the code snippet:
    -- TYPES
    TYPE content_ID_curtype IS
    REF CURSOR;
    -- VARIABLES
    c_SEARCH_STRING CONSTANT VARCHAR2(12) := 'v_content_id';
    content_ID_cur content_ID_curtype;
    v_content_ID am_content_content.content_ID%TYPE;
    BEGIN
    cache_sql_rec.sql_stmt := REPLACE(cache_sql_rec.sql_stmt, c_SEARCH_STRING, template_name_rec.content_ID);
    OPEN content_ID_cur FOR cache_sql_rec.sql_stmt;
    LOOP
    FETCH content_ID_cur
    INTO v_content_ID;
    EXIT WHEN content_ID_cur%NOTFOUND;
    END LOOP;
    CLOSE content_ID_cur;
    END;
    Now the error I get is.... ORA-00911: invalid character When I used DBMS_OUTPUT to see the actual value of
    "cache_sql_rec.sql_stmt", the SQL query looks fine. Even when I hardcoded the sql statement after the FOR keyword, it
    worked fine. It's only when I use a variable to hold the whole SQL statement does it fail. Here's one value for the
    variable cache_sql_rec.sql_stmt:
    SELECT b.content_id
    FROM am_content_mofcollection a,
    am_content_collection b
    WHERE a.content_id = 149090
    AND a.collection_id = b.collection_id;
    Basically I replace the string with an actual content_ID. Now content_ID is of type NUMBER(12) as is the variable
    v_content_ID declared so that I FETCH INTO that variable, but the problem is, is that the exception gets raised during
    the OPEN...cursor...FOR....sql_statement command.
    Any thoughts on this bug?
    Thanks,
    Gio
    Giovanni Jaramillo
    Senior Software Engineer
    Oracle Database Group
    Amplified Holdings, Inc.
    5750 Wilshire Blvd., Ste 501
    Los Angeles, CA 90036-3638
    (323)-556-8792
    [email protected] http://www.amplified.com

    Yes it turns out that the data had a semicolon at the end since it's being inserted by someone else. I know when executing DDL or DML statements via NDS you omit the semicolon. But didn't know it applied to REF CURSORS.
    Also I added a colon to the variable that I was REPLACING since it can act as a bind variable.
    Thanks Andrew.
    Gio
    null

  • Changing the Cursor Type

    Good Morning Everyone,
    I am creating a report with a barchart in a column of the report. i have been following these for reference. (mainly the first link)
    http://htmldb.oracle.com/pls/otn/f?p=31517:183:5430906720971021::NO
    http://apex.oracle.com/pls/otn/f?p=220:1:1602821811068326
    http://apex.oracle.com/pls/otn/f?p=220:2:8706839551396459
    I have sucessfully got the "progress bar" in place on my report. Now what i would like to do is change the cursor type, but im struggling.
    This is the basic lay out of the code which i am using,
              '<img src="'
           || '#WORKSPACE_IMAGES#'
           || 'green.gif" height="20" width="'
           || TO_CHAR (random_value)
           || '" '
           || 'title="'
           || TO_CHAR (random_value)
           || '% completed'
           || '" />'
           || '<img src="'
           || '#WORKSPACE_IMAGES#'
           || 'red.gif" height="20" width="'
           || TO_CHAR (100 - random_value)
           || '" '
           || 'title="'
           || TO_CHAR (100 - random_value)
           || '% open'
           || '" />' progress_barPlease could someone help me :)
    Thanks in Advance,
    -N.S.N.O.

    Hey Guys,
    Thanks for your input, i solved my problem :D The style part of the code at the bottom did the trick.
    -N.S.N.O.
    '<img src="'
    || '#WORKSPACE_IMAGES#'
    || 'green.gif" height="20" width="'
    || TO_CHAR (UKXP)
    || '" '
    || 'title="'
    || TO_CHAR (UKXP)
    || '% of tables turned on'
    || '" '
    || 'style="cursor:help";'
    || '" />'
    || '<img src="'
    || '#WORKSPACE_IMAGES#'
    || 'red.gif" height="20" width="'
    || TO_CHAR (100 - UKXP)
    || '" '
    || 'title="'
    || TO_CHAR (100 - UKXP)
    || '% of tables turned off'
    || '" '
    || 'style="cursor:help";'
    || '" />'

  • Can we register a cursor type as a folder in discoverer....

    Hi,
    I have a function that returns a cursor type variable.
    It is possible in oracle reports to make a function call and capture the "return type" of cursor type as the input to the "datamodel" using "plsql query" option, instead of a table or a query.
    Do we have any option in discoverer to get a similar effect???
    I need to call a function which returns a cursor type variable as the input to the discoverer report. How can I achieve that in discoverer???
    Any input is appreciated.
    Thanks in advance,
    Kiran

    Hi,
    Cursor types are not supported by Discoverer or Reports. This is because Discoverer needs to know the number and format of the columns that are to be displayed in the report before the report is run.
    You can work around this by defining your own type and view where the function is called from within the view. Then import the view into Discoverer and use this view in your reports.
    Rod West

  • WAd Report - How to change Cursor Type...

    Hi,
    In BI WAD report output, the cursor type is Pointer (Hand sign). I wanted to change it to some other type, is this possible, If yes, could u pls let how can i do that. I tried a lot but didn't suceed.
    Thanks...

    I think this would be possible by having custom CSS embedded in web template. E.g. see here:
    http://www.zimmertech.com/tutorials/css/20/changing-cursors-tutorial.php

  • Cursor type?

    Hey all.. the ASP connection code that DW used to generate
    listed a cursor
    type that I could change to 'optimistic' but the new code its
    spewing
    doesn't show these variables anymore.. where is it hiding
    them, or how can I
    modify what its generating to get there again (though I
    shouldn't have to?)

    Hey all.. does anyone know how to set the cursor type in this
    ASP code to
    "optimistic"?
    <%
    Dim Recordset1
    Dim Recordset1_cmd
    Dim Recordset1_numRows
    Set Recordset1_cmd = Server.CreateObject ("ADODB.Command")
    Recordset1_cmd.ActiveConnection = MM_NorthDirectory_STRING
    Recordset1_cmd.CommandText = "SELECT * FROM dbo.list_active"
    Recordset1_cmd.Prepared = true
    Set Recordset1 = Recordset1_cmd.Execute
    Recordset1_numRows = 0
    %>

  • Difference between Generic extraction and Generic Delta

    Hi Experts,
    Pleasee give of some information below  query:
    1) Difference between Generic extraction and Generic Delta.
    2) How to achieve Generic delta.
    3) When we go for Generic delta instead of generic extraction.
    Advance ThankU. Points vl be assigned.
    Thanks,
    Ragu.R

    Hi,
    Generic delta is the delta load done using Generic DS.
    Generic extraction
    Usage:
    1. When the standard extractors are not supporting the extraction what you need. If SAP does not have a standard extractor for your need to get data from R3, you would have to go for generic extractor.
    2. If you create a custom object say by combining certain base tables in R3 say custom tables ZTAB1 and ZTAB2. These two tables are not SAP provided tables and there will not be any standard extractors. So cases like this you will have to go for generic extractors.
    How:
    You have to use RSO2 transaction and you can also set delta based on, one of the three characteristics such as timestamp, calday or pointer (a sequence no).
    once you create it and activate it. The extractor will be available in ROOSOURCE - (table in R3 where all the data sources are available).
    Refer:
    /people/siegfried.szameitat/blog/2005/09/29/generic-extraction-via-function-module
    http://help.sap.com/saphelp_nw04/helpdata/en/3f/548c9ec754ee4d90188a4f108e0121/content.htm
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/84bf4d68-0601-0010-13b5-b062adbb3e33
    Generic Extraction via Function Module
    /people/siegfried.szameitat/blog/2005/09/29/generic-extraction-via-function-module
    thanks,
    JituK

  • Adding two generic number types

    Hi all,
    As a small exercise I am trying to devise a generic maths class that can add two numbers together either Integer, Float and Double types.
    I have written the following code
    class Test {
    public static void main(String args[]) {
         MathClass<Integer> integers = new MathClass<Integer>();
         Integer i= new Integer(2);
         System.out.println(integers.add(i,i));
    class MathClass<T> {
         public T add(T a, T b) {
              return a + b;
         public T subtract(T a, T b) {
              return a - b;
         public T multiply(T a, T b) {
              return a * b;
         public T divide(T a, T b) {
              return a / b;
    }But I get a compile error which says that I can't use the + - * / operators on T.
    Yet something like the following code works
    public class Test2 {
       public static void main(String[] args) {
         Integer i = new Integer(2);
         Integer o = new Integer(2);
         System.out.println(i + o);
    }Is there a way to make the generic maths class work as I would like?

    Even with the UpperBound as Number it will not be able to work as the compiler will not be able to apply autoboxing feature with Number. Number class has byteValue(), intValue(), floatValue() and doubleValue() as method, so Number class is not a spefic datatype class.
    This will work because of the feature autoboxing.
    public Integer addInteger(Integer a, Integer b) {
              return a + b;
    This will not work...
         public Number addInteger(Number a, Number b) {
              return a + b;
         }

  • A question about a method with generic bounded type parameter

    Hello everybody,
    Sorry, if I ask a question which seems basic, but
    I'm new to generic types. My problem is about a method
    with a bounded type parameter. Consider the following
    situation:
    abstract class A{     }
    class B extends A{     }
    abstract class C
         public abstract <T extends A>  T  someMethod();
    public class Test extends C
         public <T extends A>  T  someMethod()
              return new B();
    }What I want to do inside the method someMethod in the class Test, is to
    return an instance of the class B.
    Normally, I'm supposed to be able to do that, because an instance of
    B is also an instance of A (because B extends A).
    However I cannot compile this program, and here is the error message:
    Test.java:16: incompatible types
    found   : B
    required: T
                    return new B();
                           ^
    1 errorany idea?
    many thanks,

    Hello again,
    First of all, thank you very much for all the answers. After I posted the comment, I worked on the program
    and I understood that in fact, as spoon_ says the only returned value can be null.
    I'm agree that I asked you a very strange (and a bit stupid) question. Actually, during recent months,
    I have been working with cryptography API Core in Java. I understood that there are classes and
    interfaces for defining keys and key factories specification, such as KeySpec (interface) and
    KeyFactorySpi (abstract class). I wanted to have some experience with these classes in order to
    understand them better. So I created a class implementing the interface KeySpec, following by a
    corresponding Key subclass (with some XOR algorithm that I defined myself) and everything was
    compiled (JDK 1.6) and worked perfectly. Except that, when I wanted to implement a factory spi
    for my classes, I saw for the first time this strange method header:
    protected abstract <T extends KeySpec> T engineGetKeySpec
    (Key key, Class<T> keySpec) throws InvalidKeySpecExceptionThat's why yesterday, I gave you a similar example with the classes A, B, ...
    in order to not to open a complicated security discussion but just to explain the ambiguous
    part for me, that is, the use of T generic parameter.
    The abstract class KeyFactorySpi was defined by Sun Microsystem, in order to give to security
    providers, the possibility to implement cryptography services and algorithms according to a given
    RFC (or whatever technical document). The methods in this class are invoked inside the
    KeyFactory class (If you have installed the JDK sources provided by Sun, You can
    verify this, by looking the source code of the KeyFactory class.) So here the T parameter is a
    key specification, that is, a class that implements the interface KeySpec and this class is often
    defined by the provider and not Sun.
    stefan.schulz wrote:
    >
    If you define the method to return some bound T that extends A, you cannot
    return a B, because T would be declared externally at invocation time.
    The definition of T as is does not make sense at all.>
    He is absolutely right about that, but the problem is, as I said, here we are
    talking about the implementation and not the invocation. The implementation is done
    by the provider whereas the invocation is done by Sun in the class KeyFactory.
    So there are completely separated.
    Therefore I wonder, how a provider can finally impelment this method??
    Besides, dannyyates wrote
    >
    Find whoever wrote the signature and shoot them. Then rewrite their code.
    Actually, before you shoot them, ask them what they were trying to achieve that
    is different from my first suggestion!
    >
    As I said, I didn't choose this method header and I'm completely agree
    with your suggestion, the following method header will do the job very well
    protected abstract KeySpec engineGetKeySpec (Key key, KeySpec key_spec)
    throws InvalidKeySpecException and personally I don't see any interest in using a generic bounded parameter T
    in this method header definition.
    Once agin, thanks a lot for the answers.

Maybe you are looking for