Question on Generics

Consider a type-parameterized class declared as follows
public class Box<T> {
}Is there any way to get the Class object for whatever type was passed into T?
For instance I would like to be able to use something like the following code:
Box<Integer> box = new Box<Integer>();
Class<?> myClass = box.getParameterizedType();...where myClass would then be the same as what is returned by a call to Integer.class.
For the record, this is part of a reworking of a genetic programming suite I've been developing. The parametrized type in question is the return type of a node of a tree, and I am verifying if it fits the signature of some application element.

Well the Box class doesn't exist, it's merely a simplification of the problem at hand. If you want to see the body of the actual code I have written, it's something like the following:
package darwin.applicationObjects;
import java.io.Serializable;
public abstract class Node<returnType> implements Serializable {
     private static final long serialVersionUID = -1550106950846205458L;
     protected Class<?>[] childTypes;
     protected Node<?>[] childNodes;
     protected int arity;
     protected Node<?> parent;
     protected int birthOrder;
      * Instantiate a new terminal
     public Node() {
          arity = 0;
          childTypes = new Class<?>[0];
          childNodes = new Node<?>[0];
      * Instantiate a new node with child types specified
      * @param childTypes array of types of child nodes
     public Node(Class<?>[] childTypes) {
          arity = childTypes.length;
          this.childTypes = childTypes;
          childNodes = new Node<?>[arity];
      * Instantiate a new node with child nodes specified
      * @param childNodes array of child nodes
     public Node(Node<?>[] childNodes) {
          arity = childTypes.length;
          childTypes = new Class<?>[childNodes.length];
          for(int i = 0; i < childNodes.length; i++) {
               Node<?> node = childNodes;
               node.setParent(i, this);
               childTypes[i] = node.getReturnType();
          this.childNodes = childNodes;
     * Set the parent and birth order of this node to reflect the tree
     * @param birthOrder index of childNodes array to which this node is assigned
     * @param parent     reference to the parent node
     private void setParent(int birthOrder, Node<?> parent) {
          this.parent = parent;
          this.birthOrder = birthOrder;
     public Class<?> getReturnType() {
          //MAKE THIS WORK!
          return null;
     public abstract returnType getValue(Parameters p);

Similar Messages

  • Question regarding generics and collections

    Hi,
    I am stuying the Sierra and Bates book for SCJP.
    One particular answer to a question in it is puzzling me at the moment:
    Given a method as
    public static <E extends Number> List<E> process(List<E> nums)
    A programmer wants to use this method like this:
    //INSERT DECLARATION HERE
    output = process(input)
    which pairs of delcarations could be placed at //INSERT DECLARATION HERE to allow this to compile.
    Correct answers given as :
    ArrayList<integer> input = null;
    List<Integer> output = null;
    List<Number> input = null;
    List<Number> output = null;
    List<Integer> input = null;
    List<Integer> output = null;
    My main problem is understanding what this line means:
    public static <E extends Number> List<E> process(List<E> nums)
    How do I read this? I assume <E extends Number>List<E> all relates to the return type?
    If it just said List<E> I would read it as saying the return type must be a List than can only accept objects of type E but I'm confused by the extra
    part before it.
    Hope someone can help.
    Thanks

    Have you seen generics before? E is a type variable. If the method had the simpler definition:
    <E> List<E> process(List<E> nums)This would mean that E could be replaced by any type, like you had an unbounded number of definitions:
    List<A> process(List<A> nums)
    List<B> process(List<B> nums)
    List<C> process(List<C> nums)
    ...For every possible type: A, B, C, ...
    But E has the bound "extends Number" which mean that this is like have the definitions:
    List<Number> process(List<Number> nums)
    List<Integer> process(List<Integer> nums)
    List<Long> process(List<Long> nums)
    ...For Number and every subclass of Number.

  • Question about 'Generic Database Connector'

    Hi SAP IdM Gurus,
    I found 'Generic Database Connector' in the list of SAP NW IdM connectors overview.
    I'd like to check the capability of this connector in detail. 
    I'm wondering whether it could provide not only  a connectivity of RDBMS, but also custom-developed application using the RDBSM for their ID/Password repository. If it provides only a connectivity of RDBMS, Is there a connector for the custom-developed application using the RDBSM for their ID/Password repository?
    My question is that which connector is used for the connectivity  of custom-developed application using the RDBSM for their ID/Password repository.
    I would really appreciate it if you could answer the question.
    Thanks
    Kenneth

    Kenneth,
    The Generic Database connector uses a JDBC connection and allows for the and writing to databases.
    That being said, you can also use this connection to set up access to the system or drop access using SQL commands and set them up per the framework.
    What specific Database are you working with?
    Matt

  • Question about generics and subclassing

    Hi all,
    This has been bothering me for some time. It might be just me not understanding the whole thing, but stay with me ;):
    Suppose we have three classes Super, Sub1 and Sub2 where Sub1 extends Super and Sub2 extends Super. Suppose further we have a method in another class that accepts (for example) an AbstractList<Super>, because you wanted your method to operate on both types and decide at runtime which of either Sub1 or Sub2 we passed into the method.
    To demonstrate what I mean, look at the following code
    public class Super {
      public methodSuper() {
    public class Sub1 extends Super {
      public methodSub1() {
        // Do something sub1 specific
    public class Sub2 extends Super {
      public methodSub2() {
         // Do something sub2 specific
    public class Operate {
      public methodOperate(AbstractList<Super> list) {
        for (Super element : list) {
           // Impossible to access methods methodSub1() or methodSub2() here, because list only contains elements of Super!
           // The intention is accessing methods of Sub1 or Sub2, depending on whether this was a Sub1 or Sub2 instance (instanceof, typecasting)
    }The following two methods seem impossible:
    Typecasting, because of type erasure by the compiler
    Using the instanceof operator (should be possible by using <? extends Super>, but this did not seem to work.
    My question now is: How to implement passing a generic type such as AbstractList<Super> while still making the methods of Sub1 and Sub2 available at runtime? Did I understand something incorrectly?

    malcolmmc wrote:
    Well a List<Super> can contain elements of any subclass of super and, having obtained them from the list, you could use instanceof and typecast as usual.I agree with you on this one, I tested it and this simply works.
    Of course it would be better to have a method in Super with appropriate implementations in the subclasses rather than use distinct method signatures, instanceof and casting isn't an elegant solution. Alternatively use a visitor pattern.Not always, suppose the two classes have some similarities, but also some different attributes. Some getters and setters would have different names (the ones having the same name should be in the superclass!). You want to be able to operate on one or the other.
    Generics doesn't make much difference here, exception it would be more flexible to declare
    public methodOperate(AbstractList<? extends Super> list) {Which would alow any of AbstractList<Super>, AbstractList<Sub1> or AbstractList<Sub2> to be passed.I tried it and this also works for me, but I am still very, very confused about why the following compiles, and gives the result below:
    public class Main {
         public static void main( String[] args ) {
              AbstractList<Super> testSub = new ArrayList<Super>();
              testSub.add( new Sub1( "sub1a" ) );
              testSub.add( new Sub1( "sub1b" ) );
              accept( testSub );
         private static void accept( AbstractList<? extends Super> list ) {
              for ( int i = 0; i < list.size(); i++ ) {
                   Super s = list.get( i );
                   System.out.println( s.overrideThis() );
    public class Sub1 extends Super {
         private String sub1;
         public Sub1( String argSub1 ) {
              sub1 = argSub1;
         public String overrideThis() {
              return "overrideThis in Sub1";
         public String getSub1() {
              return sub1;
    public class Sub2 extends Super {
         private String sub2;
         public Sub2( String argSub2 ) {
              sub2 = argSub2;
         public String overrideThis() {
              return "overrideThis in Sub2";
         public String getSub2() {
              return sub2;
    public class Super {
         public Super() {
         public String overrideThis() {
              return "OverrideThis in Super";
    }With this output:
    overrideThis in Sub1
    overrideThis in Sub1Even using a cast to Super in Main:
    Super s = (Super) list.get( i );does not return the Sub1 as a Super (why not??)
    Sorry for the long code snippets. I definitely want to understand why this is the case.
    (Unwise, I thing, to use Super as a class name, too easy to get the case wrong).OK, but I used it just as an example.

  • Another question about generics

    Consider the following hierarchy of classes:
    class Fruit {...}
    class Orange extends Fruit {...}
    class Apple extends Fruit{...}
    Now I need to declare a collection wherein I could store any type of Fruit (including its derivated classes), but also gather some fruits.
    I hare read that for reading I need to declare the collection as follows:
    Set<? extends Fruit> fruitSet = new HashSet<Fruit>();
    and for writing I need the following declaration:
    Set<? super Fruit> fruitSet = new HashSet<Fruit>();
    My question is, is there an efficient way to declare the collection so that both operations be feasible in the class? In the current version, I use generic method and need to re-cast for some calls.
    Can anyone help?

    What they're talking about is the fact that parameterized types are not covariant. You can't treat a List<Rectangle> as a List<Shape> because they are not the same thing. Arrays on the other are covariant, you can treat a Rectangle[] as a Shape[].
    No, with your example it will not generate a compile time error, but I do see what you're getting at.
    public void readFruit(Set<Fruit> fSet) {
        // snip
    Set<Apple> fruits = new HashSet<Apple>();
    readFruit(fruits); // error because Set<Apple> is NOT a Set<Fruit>It has nothing to do with whether or not fruits contains Apples and Oranges, it's how fruits is declared. While a Set<Fruit> may contain Apples and Oranges a Set<Orange> is not a Set<Fruit>. So if you attempt to pass a Set<Orange> to a method that takes a Set<Fruit> you might as well be trying to pass an int to a method that accepts a String, they're not the same, there is no is-a relationship. So this is what you do:
    public void readFruits(Set<? extends Fruit> fSet) {
        // snip
    // All work because it will take any Set<E> where E extends Fruit.
    readFruits(new HashSet<Fruit>());
    readFruits(new HashSet<Apple>());
    readFruits(new HashSet<Orange>());What this says is that fSet can be any Set<E> where E is a subtype of Fruit. It doesn't matter what implementations the Set actually contains. If it's a Set<Fruit> and it contains Apples, it doesn't matter, it's simply allowing you to pass a Set<Apple> or Set<Orange> as opposed to only being able to pass a Set<Fruit>.

  • Cross-post: Question on generics

    Hi,
    I have just posted a question on the generics in the generics forum, but I'm also cross-posting to this forum since the generics forum is a low volume forum.
    I'd appreciate any help.
    http://forum.java.sun.com/thread.jspa?threadID=753065&tstart=0
    Kaj

    Hi @sonshine ,
    Is this still a problem for you? I'm just trying to see if I can help you on this one.  
    Best,
    Russ 
    I worked for HP.

  • Question about generic dimension in MDX for Universe

    Hi All,
      I'm testing this syntax in MDXtest and works very fine
    WITH
       SET [0COMP_CODE_MEMBERS] AS '[0COMP_CODE].[LEVEL01].members'
       MEMBER [0COMP_CODE].[MAX] AS 'Max( [0COMP_CODE].[LEVEL01].members,  [Measures].CurrentMember )'
       MEMBER [0COMP_CODE].[MIN] AS 'Min( [0COMP_CODE].[LEVEL01].members,  [Measures].CurrentMember )'
       MEMBER [0COMP_CODE].[SUM] AS 'Sum( [0COMP_CODE].[LEVEL01].members,  [Measures].CurrentMember )'
    SELECT
       NON EMPTY [0COMP_CODE].[LEVEL01].members * [0CALMONTH2].[LEVEL01].members ON COLUMNS,
       NON EMPTY AddCalculatedMembers( [0COMP_CODE].[LEVEL01].members ) ON ROWS
    from
      ZNDS_M01/ZNDS_M01_Q0001
    WHERE
      ( [Measures].[4F2TKUKDVLVTAQQ5JBLREGNJH] )
    I'm using this in one measure
    Sum( [0COMP_CODE].[LEVEL01].members,  [Measures].CurrentMember )
    But, how can I replace 
    [0COMP_CODE].[LEVEL01].
    for a generic measure?
    I need the sume depend of what the user add to the grid or select in the graph.
    How can I do this?
    Thanks.

    Hi,
    [0COMP_CODE].[LEVEL01] doesn't look like a measure to me.
    what exactly is it that you trying to do ?
    Ingo

  • A question about Generic Extractor

    Hi everyone,
    I excuted Generic Extractor to extract customer reference data to MDM server. I deselect "Local download" and  select "Upload via FTP", there is no error and the reference data was transfered to corresponsing mdm port directories. But xml files of the reference data were also downloaded into the local directory from where I upload Ports and Check-Tables.
    Could you give some suggestion about it.
    best regards,

    Hi Lionsir,
    It could be the case that you have given the local file directory address in the generate XSD option.
    Just check the same.
    Hope it helps.
    Thanks,,
    Minaz

  • A simple question about Generics

    Hello
    Why does not
    class C{
    List<Comparable> aList;
    public C(){
      aList = new ArrayList<Integer>();
    }work. Compiler says "incompatible types". Integer is a Comparable, or am I mistaken?
    Fluid

    You can suppress the warnings like this:
    public class Range {
        private List<? extends Comparable> data;
        /** Creates a new instance of Range */
        public Range(List<? extends Comparable> data) {
            this.data = data;
        @SuppressWarnings("unchecked")
        public Comparable getMax(){
            return Collections.max(this.data);
        @SuppressWarnings("unchecked")
        public Comparable getMin(){
            return Collections.min(this.data);
    }There probably is a more elegeant "generics"-solution to get rid of those warnings, but I wouldn't know how.
    P.S. you need jdk 1.5_06 for this to compile.

  • Simple question on generics.

    The following code fragment doesn't work.
    String str = "name;";
    Map<Integer, ?> map = new HashMap<Integer, Object>();
    map.put(new Integer(0), str);
    Long lval = new Long(100);
    map.put(new Integer(1), lval);
    I am looking to map integers into one of several objects. Any help would be appreciated.

    The problem is you are telling the compiler there can be objects of any type as second parameter (since any type extends Object and <?> really means <? extends Object>). That's why you are not allowed to add objects to it. Imagine if you defined it as parameter in a method, how is the compiler supposed to know what the original 2nd parameter-type was. You'd get an unchecked warning for sure if the compiler allowed it (which is obviously doesn't).
    To fix this you can use 'super' instead. With super you tell the compiler that whatever is in the list, it's can always contain an object of the type you defined as super type parameter-type:
    String str = "name;";
    Map<Integer, ? super Object> map = new HashMap<Integer, Object>();
    map.put(0, str);
    Long lval = new Long(100);
    map.put(1, lval);

  • How do I safely and correctly override equals in a generic element class?

    (I posted this in the collection forum, but it was suggested I should take it here instead.)
    I've written an OrderedPair element class, (OrderedPair<K,V>), so I can have a set of ordered pairs.
    To get the container to treat OrderedPairs as values instead of objects, I had to override OrderedPair<K,V>.equals(Object) (as hashCode too).
    So I've written the equals(Object) below in the naive way and I'm now getting warnings about an unsafe cast at line (a) and an unsafe assignemtn at line (b).
    I do understand why this is a problem, but I'm not sure what the best solution is.
    How does one ask about instanceof for the otherObject, and how does one cast an Object to an OrderedPair<K,V> in a safe way?
        public boolean equals (Object otherObject) {
         if (otherObject == null || ! (otherObject instanceof OrderedPair<K,V>)) {    //line (a)
             return false;
         } else {
             OrderedPair<K,V> otherPair = (OrderedPair<K,V>) otherObject;      // line (b)
                return this.key.equals(otherPair.key)  && this.value.equals(otherPair.value);
        }or, more to the point, how does one write a version of equals(Object) for a generic class?
    It seems that this overriding of equal will have to be done for many generic element types, so there must be some approach that is safe, yes?
    It was pointed out to me that AbstractMap does something similar

    <warning: thread hijack>
    public class OrderedPair<A,B> {
    final A a;
    final B b;
    A first() {
            return a;
    B second() {
       return b;
    another question about generic code is this:
    is it possible that , most of the time, a generic code may looks like this
    (please note that this is not a criticism of the above code which is perfectly ok to me):
    public class OrderedPair<A,B> {
      public final A a;
      public final B b; // no accessor such as getA(), getB()
    my point : unless you want specific behaviour linked to value consultation
    the actual type of members a and b is not hidden: encapsulation seldom makes sense.
    it is known to the user of the parametrized type, it is not subject to maintenance change
    so it is public ..... (if it is final)
    any remark?

  • Generic Datasource

    Hi
    I have a question regarding generic datasource based on function module... Is it possible to have 2 differents function modules based on the same extract structure (Z1)?
    I have one existing datasource (DS_A) based on a function module (FM_1) and extract structure (Z1)
    Since I have to change the functionality on the existing function module (creating FM_2) for another datasource (DS_B), I am wondering if the 2 datasources (DS_A and DS_B) could be based on the same extract structure(Z1) created previously for datasource (DS_A)
    Thanks!!

    hi,
    this can be done however this will always create a dependency, like if you have to change Z1 due to one FM1 (like addition of new field) then you need to enhance the code for FM2 as well as e_t_data inFM2 will have the structure same as Z1.
    its better to create a copy of the existing strucutre Z1 and use it in Fm2.
    regards,
    Arvind.

  • Generic delta; When R/3 record deleted.

    Hi all
    Please tell me What will happen to the BW record when the record in R/3 add-on table is deleted and the data is retrieved by generic delta.
    (1)At the beginning.
    R/3                         BW
    20051124000001   100$   ->  20051124000001   100$  
    (2)Then, R/3 record deleted.Does the record on BW will be deleted or remain in same?
    R/3 record deleted      ->  BW record also deleted
                            or 
    R/3 record deleted      ->  20051124000001   100$  
                                remain in same
    Now, I cannot access to BW; I couldn't test by myself. So, I wish someone help me.
    Ken'ichi

    Hi Ken'ichi,
    Refer these posts on RECORDMODE:
    Re: ods-  0 Record mode
    Re: 0RECORDMODE Question
    A generic datasource can be based on:
    1. View/Table
    2. Function module extractor
    3. Infoset query.
    You would find many links on the same topic in these forums. Kindly use the search option.
    Bye
    Dinesh

  • Business content question

    Hi all,
    can anybody suggest me any answer on these question know generic data extraction but don't know how to use standard business content.
    1 ) How to find right business content of given requirement.
    2 ) How to use standard business conent if any example then tell me
    3 ) Is in BW any standard business content is present for Material management if yes then tell me how to use by example.
    If any link or any example through which i clear my doubts then let me know.
    Regards
    Ankit

    You get the business contents in transaction RSORBCT.
    You can also get info on them on help.sap.com

  • Question on Product Registration

    (Apologies ahead of time if this is the wrong place to ask--
    please let me know where I should go?)
    My company bought 10 licenses of Master Collection for PC,
    which included several spares. I want to install it on my mac at
    home. Can I just download the trial for mac and use my license
    code, or will I run into a problem?
    Thanks!

    Thanks for the reply.
    For the time being, I'm limited to a PPC and can't use software designed for Intel chips. This is my issue. It's really not about finding a cleaver & inexpensive pathway to upgrades. Would love a new MacPro, but that's not in my immediate future.
    The old software I'm looking into is Final Cut Studio 2 (or FCS 5.1), as FCS 3 does not work on a PPC. So, I'm limited to after market options, which are full of potential problems and shady characters. I'm sure some folks don't really know the history of the product they're selling (e.g. a pawn shop). Honestly, this strategy is not my favorite idea, but I am doing my due diligence as best I can.
    I didn't post my question on the FCS/Pro forums because I thought my question was generic and applied to any Apple software product.

Maybe you are looking for

  • Is someone trying to send SPAM through one of my servers?

    Hey all. I had a rather fun start to the week, my boss handed me a couple pages of an email he got that had bounced back from our ISP. Basically it tried to send mail to a "[email protected]" (googled it: apparently people get phishing messages from

  • How do I recover a corrrupt iPad Garageband file

    Have been working on a track for a few days, drums bass precussion to use as a backing track. Closed the file this afternoon then reopened it to make a small change. Think I might have opened it too quickly. Now when I open it the loading bar opens u

  • Fix Business Role / Technical Role assignment in Pending or Failed status

    Hi, We are facing issues with few users where Business role assignment or technical role assignment is going into Pending or failed status. None of the jobs are failing or throwing any error related with the changes. We are running IdM 7.2 version wi

  • Transfer iPhoto Events to Photo

    I have been asked by the Apple Applications App to upgrade from Yosemite 10.10.2 to 10.10.3. This update will install the new Photos App. I am concerned that I will loose my current system of filing my photos which is based upon filing all my photos

  • Transactional Iviews are not showing ( with out super admin role assigned )

    Please any solutions for the fallowing. First Problem I am not able to create the user from portal directly. Its showing the fallowing error. An error occurred in the persistence; contact your system administrator. so i had created the users in WAS b