Passing Class T to a generic MyClass T 's constructor

I have a class like this:
class MyClass<T> {
    Class<T> theClass;
    MyClass(Class<T> theClass) {
        this.theClass = theClass;
}This would require the following code to instantiate:
MyClass<String> myClass = new MyClass<String>(String.class);Correct? This is the simplest syntax for creating the class? It seems redundant to have to pass the type "String" twice when constructing the class. I understand constructors can have type parameters like methods, but that type parameter doesn't translate the T parameter to the class, so that won't work.
I tried the following solution:
class MyClass<T> {
    Class<T> theClass;
    MyClass(Class<T> theClass) {
        this.theClass = theClass;
    public static MyClass<T> create(Class<T> theClass) {
        return new MyClass<T>(theClass);
}This allows for the syntax:
MyClass<String> myClass = MyClass.create(String.class);Which seems more elegant. Of course, the obvious problem with doing this is that it makes subclassing of MyClass much more difficult. Sometimes I can get away with this workaround, more often I cannot. Have I missed anything?

Let's be real here. We are talking about a single line of code. Not a huge class.
You have to change the one if you change the other. There's no danger of one
getting left behind.I don't agree. The nature of creating a class is that for every class you create, there will be one or more (usually more, sometimes MANY more) users of that class. If it were a class like StringBuffer that is used in a million places, then you are making code less redundant for each one of those use cases, and all you had to do was add a factory method.
You are creating a factory method on you class because of distaste for a
syntactical construct. You don't see how this factory method changes the
design?In a strict sense, yes, it impacts the design inasmuch as adding a method changes the contract of the class. However, I don't see how it makes any practical difference in the design.
Are you going to create this factory method for every class that has this kind of
situation? I imagine someone is going to come along later to maintain the
code and think "what the..?" Yeah, and they'll click on "Go to definition" in their IDE and see the extremely complicated method:
public static <U> create(Class<U> theClass) {
    return new MyClass<U>(theClass);
}If they can't understand that, they don't understand generic code and probably shouldn't be mucking around there anyway.

Similar Messages

  • How to pass class object  as in parameter in call to pl/sql procedure ?

    hi,
    i have to call pl/sql proecedure through java. In pl/sql procedure as "In" parameter i have created "user defined record type" and i am passing class object as "In" parameter in call to pl/sql procedure. but it is giving error.
    so, anyone can please tell me how i can pass class object as "In" parameter in call to pl/sql procedure ?
    its urgent ...
    pls help me...

    793059 wrote:
    I want to pass a cursor to a procedure as IN parameter.You can use the PL/SQL type called sys_refcursor - and open a ref cursor and pass that to the procedure as input parameter.
    Note that the SQL projection of the cursor is unknown at compilation time - and thus cannot be checked. As this checking only happens at run-time, you may get errors attempting to fetch columns from the ref cursor that does not exist in its projection.
    You also need to ask yourself whether this approach is a logical and robust one - it usually is not. The typical cursor processing template in PL/SQL looks as follows:
    begin
      open cursorVariable;
      loop
        fetch cursorVariable bulk collect into bufferVariable limit MAX_ROWS_FETCH;
        for i in 1..bufferVariable.Count
        loop
          MyProcedure( buffer(i) );   --// <-- Pass a row structure to your procedure and not a cursor
        end loop;
        ..etc..
        exit when cursorVariable%not_found;
      end loop;
      close cursorVariable;
    end;

  • Is possible pass class reference into function by reference ?

    Hello, here is one example.
    class MyClass
    public int i;
    public static void Change(MyClass param1, MyClass param2)
    MyClass temp;
    temp = param1;
    param1 = param2;
    param2 = temp;
    public static void main(String[] args)
    MyClass param1 = new Main();
    param1.i = 100;
    MyClass param2 = new Main();
    param2.i = 200;
    Change(param1,param2);
    System.out.println(param1.i);
         System.out.println(param2.i);
    Is clear the result will be :
    100
    200
    Well, is possible in java pass into function object reference by reference? (for example in C# exist keyword ref, which solve this problem.) Other question is if this is something what is really needed in daily programming life, but I'm curious.
    Thanks for response

    iaragorn wrote:
    Well, is possible in java pass into function object reference by reference? No. Java only passes by value.
    Other question is if this is something what is really needed in daily programming lifeNope. Java has done just fine without pass by reference for about 12 or 14 years now.

  • Confused about creation of inner class object of a generic class

    Trying to compile to code below I get three different diagnostic messages using various compilers: javac 1.5, javac 1.6 and Eclipse compiler. (On Mac OS X).
    class A<T> {
        class Nested {}
    public class UsesA <P extends A<?>> {
        P pRef;
        A<?>.Nested  f() {
            return pRef.new Nested();  // warning/error here
    Javac 1.5 outputs "UsesA.java:11: warning: [unchecked] unchecked conversion" warning, which is quite understandable. Javac 1.6 outputs an error message "UsesA.java:11: cannot select from a type variable", which I don't really undestand, and finally the Eclipse compiler gives no warning or error message at all. My question is, which compiler is right? And what does the message "cannot select from a type variable" means? "pRef", in the above code, is of a bounded type; why is the creation of an inner object not allowed?
    Next, if I change the type of "pRef" to be A<?>, javac 1.6 accepts the code with no error or warning message, while javac 1.5 gives an error message "UsesA.java:11: incompatible types" (concerning the return from "f" above). Similarly to javac 1.6, the Eclipse compiler issues no error message. So, is there something that has changed about generics in Java between versions 5 and 6 of the language?
    Thanks very much for any help

    Checkings bugs.sun.com, it seems to be a bug:
    http://bugs.sun.com/view_bug.do?bug_id=6569404

  • LVOOP technique for passing classes down to subVIs

    Hello LVOOP experts,
    A quick question regarding performance of LVOOP. I finally got around to implementing something non-trivial with LV classes, just for fun though.
    If my architecture consists of a state machine, with a typedef'ed shift-registered cluster (containing all my core classes) being passed around the main loop and into subVIs, is there a performance penalty if the classes contain lots of data?
    My question arises from my only passing knowledge of how LV classes work. As they are byvalue, does this mean ALL the data gets copied/moved between every state, and into every subvi? Or is the compiler smart enough to know that if I am passing the main cluster into a subVI it doesn't necessarily need to make a copy of the data unless I am forking it or something.
    Fictional example, one of the classes is a data storage and has 1M DBL values in it, is this going to cause lots of memory allocation? (If so then its better probably to not store the data directly in the class, rather have a queue or some other byref storage, right?)
    Comments appreciated :-)
    n
    nrp
    CLA

    nrp wrote:
    Mark Yedinak wrote:
    My understanding is that LVOOP objects are passed by value. So you would indeed take a hit if you are passing large objects around.
    Thats as much as I suspected, thanks for the confirmation.
    My big problem is I have not seen a reference implementation of how to do it right. I sure wish NI would provide some intermediate example rather than dog/cat or car/truck.
    The closest I have seen in DfGrays Xylophone set of tutorials, but then he complicates things by using a singleton type approach (dequeue --> use object --> requeue) and a strange (to me) architecture with lots of registered events and an event structure as one of the cases of the main state machine loop.
    Does anybody have a non-trivial, but freely distributable example of doing classes the right way? I know there are probably a dozen or so ways of doing it right, but there must be some common ground.
    I spent the weekend mucking about and have something which I will present once I have tidied it up a bit.
    But the overhead is probably negligible for non-storage type classes, i.e. the classes that define the
    HI Mark and Neal (?)
    The Pass by value story is starting to shape as a misnomer (sp? bad name).
    1) If I do a Show buffer allocations when a class wire splits, the buffer does not show-up under clusters of array but rather as a scalar.
    2) You can type cast the class ref as a U32 and you get a number.
    3) When using Dynamic Dispatching you have to have the class control and indicator on the icon connector, so all of the requirements are present for the sub-VI (method) to work in-place using the bufer that was pointed to by the caller.
    So passing the data in a class is about the same as when working with clusters. If LV can avoid the copy it will.
    But where you will take a hit...
    When we fork a class wire there is a buffer allocated. Too many splits could cause problems. As long as we string together lines of VLOOP methods, they should use the same buffer.
    BTW:
    I did have to do a re-write of one of my early LVOOP projects because I was splitting a class with a Image data in it. The re-wire skipped using the class and just passed the image data (via a queue between threads).
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Pass Class Object To FMS Using NetConnection.call Method

    Hello All,
    I have a custom class that defines several methods on itself
    to retrieve its data. This class object is then sent to FMS via the
    NetConnection.call method. Once received by FMS, FMS calls the
    remote method to dispaly the class object on connected clients
    (minus the originator).
    Now, standard properties are displayed correctly, but when I
    call the class method to retrieve the class data, no data is
    retrieved.
    My question is, can FMS handle class objects as parameters in
    a NetConnection call. If not, is there a better practice of
    applying methods to retrieve the class data? Example below...
    class com.QuizItem
    var numOfAnswers;
    var getAnswer;
    function QuizItem(question)
    this.numOfAnswers = 0;//<-- Returns correct number of
    answers
    this.getAnswer = function(answerNumberToGet)//<-- Does
    not return any data when called by client side script
    return this.answers[answerNumberToGet];//Already populated
    array
    Regards,
    Shack

    First, I know JAVA does not working "pass by
    reference". It's only working pass by value. (or call
    by value)But obviously you don't fully understand what it means.
    Isn't main_a and method_a alias?
    if there is not alias, why? please explain to me.No. They're two independent references coincidentally pointing to the same object. In your swap method, you move method_a to point to something else. This does not affect main_a.
    and why main_a.hashcode() is main_a's value?why not? What else should it be?
    I think It's mean copy object. but main_a and
    method_a, they have same object id! @_@;;;It means "copy reference", same object.

  • Passing class dynamically to the session.createCriteria()

    I'm using hibernate.and is now creating a common search class. For that I need to pass the class name to the session.createCriteria() dynamically. I have tried passing the name by string . But it doesn't work. How to do it.
    Plz help. Thanks in advance

    Hi Sandeep,
    This is possible.
    For creating filenames dynamically for your sender, you will have to crate a variable name ( eg: %VAR%) as you file name and then you will have to give the name of your file under variable substitution. Just check this link for more info,
    http://help.sap.com/saphelp_nw04/helpdata/en/14/80243b4a66ae0ce10000000a11402f/frameset.htm
    In the case of receiver file adapaters, you have 5 options for file creation like,
    1.Create
    2.Append
    3. Add time stamp
    4.Add Counter
    5. Add Message ID
    You can choose any of these options or you can do it dynamically from you payload. Just check out this help link for more info,
    http://help.sap.com/saphelp_nw04/helpdata/en/14/80243b4a66ae0ce10000000a11402f/frameset.htm
    Hope this helps

  • CX_SHM_EXTERNAL_REFERENCE exc. when passing Class instance to Shared memory

    Hi all,
    when setting up the writing to a shared memory (using the SHMA and SHMM transactions), we get an exception mentioning CX_SHM_EXTERNAL_REFERENCE
    This problem is raised because we are trying to move an instantiated class from the calling development to the Shared memory class.
    Therefore, this exception is raised, the sap standard documentation tells me:
    "There are still references from the current area instance version to a different area instance of the shared objects memory, or to the internal session."
    How can we work around this problem, I really want to pass the instantiated class to the Shared memory?
    Thanks in advance for any help,
    Pascal Decock

    My problem is that I would like to embed a Standard SAP class into this shared memory.
    Therefore, I'm obliged to accept the 'Create object' references that are written in standard SAP code.
    That also means that it is impossible to include an instantiated SAP class into a shared object memory?

  • Sample Javadoc comments for classes or methods using generics?

    Can anyone show me a sample Javadoc comment for a class or a method that uses generics. All my attempts so far ended up in warnings from the Javadoc tool..
    I also looked in the Sun forums, in the Javadoc documentation, but nowhere could I find anything that would help me write correct javadoc comments.
    Any luck for you guys?
    Thanks a lot,
    -Laurent

    Thanks man, sorry it must seem obvious to you, but
    for some reason I couldn't get it to work.No. The first time I also had to ask.
    Now an even more difficult (for me) question: how
    would you refer to that method in a @see or {@link
    ..} javadoc comment?Manually erase the method:
    * The see tag refers to this method
    * @param <T> a type variable
    * @see #foo(Object)
    <T> void foo(T t) {}

  • How can a genericized class determine its own generic type?

    Hi, I have a generecized class:
    class Foo<T> {
        public Class myClass() {
           // basically want to return T.class
    }Is there a way to do this?
    What if Foo implements FooIF, which is also paramterized with T, can I then use this.getClass().getGenericInterfaces() to find ParametrizedType and cast it to class?
    Thanks,
    Konstantin

    Hi, I have a generecized class:
    Is there a way to do this?
    class Foo<T> {
        private Class<T> myClass;
        public Foo(Class<T> t){
             myClass=t;
    }>
    What if Foo implements FooIF, which is also
    paramterized with T, can I then use
    this.getClass().getGenericInterfaces() to find
    ParametrizedType and cast it to class?If you do class Foo<T> implements FooIF<String> then you can get String back (but you don't cast ParametrizedType), otherwise that will just give you "T".

  • Using reflection on passed classes

    Hello,
    I have been trying to write a common function to return the variables and values of a class passed into it. The function uses reflection to iterate through the Fields and returns a string of the variables and values. Is it anything to do with scope, as the same code works when I paste the method into the class I am looking at (See below)?
    I have pasted the code fragments below.
    Thanks
    stuart
    * Returns XML fragment of name value pairs of member/value
    * @param iClass the class under inspection
    * @return XML fragment of name value pairs of member/value
    public static String inspectMemberVariables(Class iClass)
    String oStr = new String();
    try
    Class c = iClass.getClass();
    Field[] f = c.getFields();
    System.out.println(f.length);
    for (int i=0; i < f.length; i++)
    // identify the field
    Field fld = c.getField( f.getName());
    //get the field name and grab the field value from the class
    oStr += f.getName()
    + "=\""
    + fld.get(c)
    + "\" ";
    } // for (int i=0; i < f.length; i++)
    oStr = "classname=\""
    + c.getName()
    + "\" "
    + oStr;
    } //end of try
    catch (NoSuchFieldException e)
    System.out.println(e);
    catch (SecurityException e)
    System.out.println(e);
    catch (IllegalAccessException e)
    System.out.println(e);
    } //end of catch
    return oStr;
    } // end ofinspectMemberVariables
    Where the code is called:
    public class ReflectionTest extends PPSpposEBCore
    public String strg;
    public ReflectionTest()
    String str2 = new String ();
    str2 = ClassProperties.inspectMemberVariables(this.getClass());
    System.out.println(str2);
    public static void main(String[] args)
    String str = new String ();
    try
    ReflectionTest rt = new ReflectionTest();
    // set dummy values to test
    rt.mPossessionId = 12;
    rt.mBusinessPossRef = "look it works";
    rt.mCreatedTs = new Date();
    //ClassProperties cp = new ClassProperties();
    //str2 = ClassProperties.inspectMemberVariables(rt.getClass());
    Class c = rt.getClass() ;
    Field[] f = c.getFields();
    System.out.println(f.length);
    for (int i=0; i < f.length; i++)
    // identify the field
    Field fld = c.getField( f.getName());
    //grab the field name and field value from the class
    str += f.getName()
    + "=\""
    + fld.get(rt)
    + "\" ";
    } // for (int i=0; i < f.length; i++)
    str = "classname=\""
    + c.getName()
    + "\" "
    + str;
    System.out.println(str);
    } //try
    catch (NoSuchFieldException e)
    System.out.println(e);
    catch (SecurityException e)
    System.out.println(e);
    catch (IllegalAccessException e)
    System.out.println(e);

    sorry it doesn't work, interface cannot have method body, i didn't know it. You couldn't access to private and protected datas with an exterior method. You can make a package with classes you want to inspect and a class who inspect. The classes of a package can access to protected datas.

  • How to get a Class object with a generic type of list

    Hi,
    I want to get an instance of a class which is of type List<ABC>. How can I get that ?
    What I tried was Class c = List<ABC>.class , bu this is not compiling. I can get new ArrayList<ABC>().getClass() , but the type of that class would be Class<? extends ArrayList<ABC>> but not what I want Class<? extends List<ABC>> ...
    Thanks in Advance.
    Bhargava

    Thanks for so many responses. I understand that you can not get a class instance of type Class<List<E>>. Am I correct?
    My use case was something like this:
    Class X implements Y<SrcType, DescType> {
      public DestType transform(SrcType src) { ---- }
    }Now I want to write a factory which maintains a list of implemenrations of interface Y in a map. For e.g. {List(SrcType,DestType) -> X}. This factory provides one method with the following signature:
    Class Yfactory {
       public Y transform(SrcType o, Class destType) {
        //This figures out which transformer to apply based on SrcType and destType and gives it back.
    }Now, there is one case where a transformer transforms from type A to List<B> (X implements Y<A, List<B>>) . How should I add it to the map in factory and how do I call the factory's transform method so that it choose this transformer?

  • How to get CLASS name for the generic item?

    Hi,
    I wrote following method to create a service instance.
    public static <IType> IType GetServiceInstance()
           IType type=null;
            try
            InitialContext ic=new InitialContext();
    //ERROR:      type=   ic.lookup(IType.class.getName());
            catch(Exception ex)
            //do handle
            return type;
        }please see the //Error: here its giving error, also i m not getting "class" variable in IDE!!!
    i want use like this;
    IUserService userService=ServiceFactory.GetServiceInstance<IUserService>();so how can i do this?
    Edited by: Manikandan.Java on Oct 31, 2007 3:02 AM

    I don't know if I understand your question, but you cannot find the class name because it is in run time just an object. You can, however, check if it is an instanceof.
    if (genericType instanceof MyType) {
         doMyThing();
    }

  • Need help badly to pass class

    If anyone could help me write this thing using simple loops I swear i would dance at there wedding. This is my last class to graduate college with a bachelors and I am so computer stupid. If anyone could write out this code for me or just help me get started with my main method i would appreciate it so much. The java problem that I have to write a program to is below and I am sorry it is alot of question to a novice programmer like myself I am so lost please help!!!!!!!!!!!!!
    Write a java class called factorNumber that gets a whole number from the user and determines its divisors. It should return the results in a dialog box with a message like: The factors of 25 are 1,5,25.
    Place this code in a large loop so the user can check as many numbers as they like. Also put in error checking. If the user enters a nonpositive iteger, give them an error message and prompt for another number. If at any point the user clicks on the cancel button for any dialog box exit the program.
    When that is working, add more fuctionality to your program. Check the given number for the following conditions.
    1.prime number(only divisible by 1 and itself. 1 is not considered to be prime.)
    2.perfect number(it is the sum of its factors up to but not including itself; ex" 6 is a perfect number because its factors are 1,2,3 and 1+2+3=6.
    3.perfect square(it is the square of some other whole number)
    if any of these conditions are satisfied, include that information in the message to the user. Respond with message:
    The factors of 25 are 1,2,25
    25 is a perfect square.
    or
    the factors of 6 are 1,2,3,6.
    6 is a perfect number.
    I Ammmmmm so lost how do i white this thing????????????/

    i hope i can get something out of this:
    import java.io.*;
    class FactorNumber
         public static void main(String[] args)
              int base = 0;
              int y=0;     
              double z;
              float w;
              try{
              System.out.println("Enter the base : \t " );                         
              BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
              base = Integer.parseInt(br1.readLine());          
              System.out.println("the factors are:");
              for(int x=1;x<=base; x++ ){
              if(base%x==0){
                   System.out.print(x+" ");
                   y=y+x;
                   if(y==base){System.out.println("\nThis is a perfect number");}
              z = Math.sqrt(base);
              w=Math.round(z);          
              if(z%w==0){
              System.out.println("\n"+base+ " is a perfect square");
              }catch (IOException e){System.out.println("The error" + e);}
    }

  • Class implementing interface using generics

    I have an interface that looks like this:
    public interface BinaryTree<T extends Comparable<? super T>> {
         public enum TraverseOrder { PREORDER, INORDER, POSTORDER }
         public boolean isEmpty();
         public boolean search(T key);
         public void remove ( T key ) throws TreeException;
         public void insert(T key) throws TreeException;
         public void print ( TraverseOrder order);
         public int getSize();
    }My shell class that implements it looks like this:
    public interface BinaryTree<T extends Comparable<? super T>> {
         public enum TraverseOrder { PREORDER, INORDER, POSTORDER }
         public boolean isEmpty(){
                      return true;
         public boolean search(T key) {
                      return true;
         public void remove ( T key ) throws TreeException {
         public void insert(T key) throws TreeException {
         public void print ( TraverseOrder order) {
         public int getSize() {
                        return 0;
    }Im getting 2 errors one being
    BST.java:1: > expected
    public class BST implements BinaryTree<T extends Comparable<? super T>> {
    and the other is an enum error. Im pretty sure the second enum error will be resolved by fixing the first error. Any help is apreciated. Thanks
    BLADE

    Yeah tottaly right but the code i posted is wrong sorry lets try one more time
    public interface BinaryTree<T extends Comparable><? super T>> {
         public enum TraverseOrder { PREORDER, INORDER, POSTORDER }
         public boolean isEmpty();
         public boolean search(T key);
         public void remove ( T key ) throws TreeException;
         public void insert(T key) throws TreeException;
         public void print ( TraverseOrder order);
         public int getSize();
    public class BST implements BinaryTree<T extends Comparable><? super T>> {
         public enum TraverseOrder { PREORDER, INORDER, POSTORDER }
         public boolean isEmpty(){
                      return true;
         public boolean search(T key) {
                      return true;
         public void remove ( T key ) throws TreeException {
         public void insert(T key) throws TreeException {
         public void print ( TraverseOrder order) {
         public int getSize() {
                        return 0;
    }

Maybe you are looking for

  • Campos de entrada não obrigatório no Crystal Reports- Chamada por Procedure

    Olá a todos. Estou desenvolvendo relatórios em crystal para o B1 8.8.  os retornos de dados são realizados através de procedures desenvolvidas no sql. O problema é que não sei como posso estar fazendo para que determinados campos de minha tela de cha

  • GR/IR GL Account for Non-stock(consumption items)

    Dear All, I understand that for Valuated materials, system will grab the GR/IR GL Accounts from OBYC--> WRX based on the valuation classes. However, how about Short text items or Non-valuated materials (Items with no Valuation Class) where you use Ac

  • Streams Propagation Job --next_date := sys.dbms_aqadm.aq$_propaq(job)

    I have implemented oracle 1 way db replication from db "A" to db "B" using oracle streams. The config is running okay but I see this plsql block always increasing in time . It is the Propagation job. The total time value presently is at 15121 secs .

  • Adding a Shadow 3D

    I'm trying to create a shadow but I'd like to make it so it appears like it's in 3D. The shadows utility under Layer Style makes a shadow as if the object would be floating on top of the other layer. But what if I would like to make it appear as if i

  • Separate thread for input stream and output stream.

    Hi Techies, In a socket connection, can we run the input stream and output stream in separate threads. actually in my case, the input stream will be getting the input regularly and output stream will send data very rare. so if i impelment them in one