dermetfan

Java generic types

Jul 14th, 2013
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. package net.dermetfan.someLibgdxTests;
  2.  
  3. public class MyGenericClass<T> { // "T" stands for "Type"; you could also write Type completely, but T is commonly used
  4.    
  5.     public T myGenericField; // this field is going to be of the class that the user puts as T
  6.    
  7.     public T myInitializedGenericField = (T) new Object(); // everything has to be cast to T here because we cannot know what class T is going to be
  8.  
  9.     public String getNameOfT() {
  10.         return myGenericField.getClass().getSimpleName(); // the name of the T class (could also be a subclass if the user puts a subclass of T in)
  11.         // If T was String, "String" would be returned.
  12.         // If T was Integer, "Integer" would be returned.
  13.     }
  14.  
  15.     public void setMyGenericField(T thing) { // You can only put objects of the type of T in here. T was set when an instance of this class was created.
  16.         myGenericField = thing;
  17.     }
  18.    
  19.     public void setMyGenericFieldAgain(Object thing) {
  20.         myGenericField = (T) thing; // have to cast to T again, see comment near myGenericField; this could cause a ClassCastException if thing cannot be cast to the type of T
  21.     }
  22.    
  23.     public T getMyGenericField() { // T because we cannot know what class myGenericField is going to be of yet
  24.         return myGenericField;
  25.     }
  26.  
  27.     public T getACastThing(int index) {
  28.         Object[] arrayOfStuff = new Object[] {"a String", 1, new StringBuilder()}; // an array of some things
  29.         /* In case T was String and index was 0, this method would return "a String".
  30.          * In case T was String and index was 1, a ClassCastException (or something) would be thrown.
  31.          * In case T was Object, index can be 0 to 2. You can cast anything to object. */
  32.         return (T) arrayOfStuff[index];
  33.     }
  34.    
  35. }
Advertisement
Add Comment
Please, Sign In to add comment