Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package net.dermetfan.someLibgdxTests;
- public class MyGenericClass<T> { // "T" stands for "Type"; you could also write Type completely, but T is commonly used
- public T myGenericField; // this field is going to be of the class that the user puts as T
- 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
- public String getNameOfT() {
- return myGenericField.getClass().getSimpleName(); // the name of the T class (could also be a subclass if the user puts a subclass of T in)
- // If T was String, "String" would be returned.
- // If T was Integer, "Integer" would be returned.
- }
- 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.
- myGenericField = thing;
- }
- public void setMyGenericFieldAgain(Object thing) {
- 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
- }
- public T getMyGenericField() { // T because we cannot know what class myGenericField is going to be of yet
- return myGenericField;
- }
- public T getACastThing(int index) {
- Object[] arrayOfStuff = new Object[] {"a String", 1, new StringBuilder()}; // an array of some things
- /* In case T was String and index was 0, this method would return "a String".
- * In case T was String and index was 1, a ClassCastException (or something) would be thrown.
- * In case T was Object, index can be 0 to 2. You can cast anything to object. */
- return (T) arrayOfStuff[index];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment