歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中關於泛型擦除的小結

Java中關於泛型擦除的小結

日期:2017/3/1 10:31:16   编辑:Linux編程

java由於擦除,在使用泛型的時候一些操作成了程序存在異常的可能 ,這個類中展示了一些容易出現的問題,下面的小例子做了一個簡單的總結

  1. class Erased<T> {
  2. public static void f(Object arg) {
  3. // if (arg instanceof T) {
  4. // } // Error
  5. // T var = new T(); // Error
  6. // T[] array = new T[SIZE]; // Error
  7. // T[] array = (T) new Object[SIZE]; // Unchecked warning
  8. }
  9. }

下面的程序算是對擦除特性的一個彌補

  1. /*casionally you can program around these issues, but sometimes you must compensate for erasure by introducing a type
  2. * tag . This means you explicitly pass in the Class object for your type so that you can use it in type expressions.
  3. * For example, the attempt to use instanceof in the previous program fails because the type information has been
  4. * erased. If you introduce a type tag, a dynamic islnstance( ) can be used instead:
  5. */
  6. public class CompensatErasure<T> {
  7. public static void main(String[] args) {
  8. CompensatErasure<Building> ctt1 = new CompensatErasure<Building>(Building.class);
  9. ctt1.f(new Building());
  10. ctt1.f(new House());
  11. CompensatErasure<House> ctt2 = new CompensatErasure<House>(House.class);
  12. ctt2.f(new Building());
  13. ctt2.f(new House());
  14. }
  15. private Class<T> type;
  16. public CompensatErasure(Class<T> type) {
  17. this.type = type;
  18. }
  19. /**
  20. * @return the type
  21. */
  22. public Class<T> getType() {
  23. return type;
  24. }
  25. /**
  26. * @param type
  27. * the type to set
  28. */
  29. public void setType(Class<T> type) {
  30. this.type = type;
  31. }
  32. @SuppressWarnings("unchecked")
  33. public void f(Object obj) {
  34. // Compensate instance of
  35. if (type.isInstance(obj)) {
  36. System.out.println(obj + " is instance of " + type.getSimpleName());
  37. } else {
  38. System.out.println(obj + " doesn't instance of " + type.getSimpleName());
  39. }
  40. try {
  41. // Compensate new T();
  42. System.out.println(type.newInstance());
  43. // compensate new T[]{};
  44. Class<T>[] types = new Class[1];
  45. } catch (InstantiationException e) {
  46. e.printStackTrace();
  47. } catch (IllegalAccessException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. }
  52. class Building {
  53. @Override
  54. public String toString(){
  55. return "Building";
  56. }
  57. }
  58. class House extends Building {
  59. @Override
  60. public String toString(){
  61. return "House";
  62. }
  63. }

Copyright © Linux教程網 All Rights Reserved