Advertisement
Guest User

Untitled

a guest
Mar 30th, 2015
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package zad2;
  7.  
  8. import java.lang.reflect.Array;
  9. import java.lang.reflect.Constructor;
  10. import java.lang.reflect.InvocationTargetException;
  11. import java.util.logging.Level;
  12. import java.util.logging.Logger;
  13.  
  14. /**
  15.  *
  16.  * @author Kamil
  17.  * @param <T>
  18.  */
  19. public class GenericSample<T> {
  20.  
  21.     Class t,t2;
  22.    
  23.     public GenericSample(Class<T> c) {
  24.         t=c;
  25.         t2=this.getClass();
  26.     }
  27.    
  28.     public T getTNewInstance(){
  29.         try {  //Class c = Class.forName(this.getClass().getTypeParameters()[0].getTypeName());
  30.             return (T) t.newInstance();
  31.         } catch (InstantiationException | IllegalAccessException ex) {
  32.             Logger.getLogger(GenericSample.class.getName()).log(Level.SEVERE, null, ex);
  33.         }
  34.         return null;
  35.     }
  36.    
  37.     public T[] getTArray(int size){
  38.         return (T[]) Array.newInstance(t, size);
  39.     }
  40.    
  41.     public GenericSample<T> getGSTNewInstance(){
  42.         try {
  43.             return (GenericSample<T>) t2.getConstructor(Class.class).newInstance(t);
  44.         } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
  45.             Logger.getLogger(GenericSample.class.getName()).log(Level.SEVERE, null, ex);
  46.         }
  47.         return null;
  48.     }
  49.    
  50.     public GenericSample<T>[] getGSTArray(int size){
  51.         return (GenericSample<T>[]) Array.newInstance(t2, size);
  52.     }
  53.  
  54.     @Override
  55.     public String toString() {
  56.         return "GS<"+t.getSimpleName()+">@"+this.hashCode();
  57.     }
  58.  
  59.  
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement