محو الأنواع
في هذا الدرس 4 موضوعات
هذا الدرس مخطط له. يعرض المخطط أدناه الموضوعات التي سيغطيها، ولم يُنشر الدرس الكامل بعد.
نص الدروس والتمارين باللغة الإنجليزية، بينما تبقى واجهة الموقع وعناوين الدروس بالعربية.
في هذا الدرس
explain what generics are at runtime and the consequences.
الموضوعات المخطط لها
- Generic type arguments are checked at compile time, then erased; at runtime
List<String>is aList. - Consequences: no
new T(), noinstanceof List<String>, no generic arrays, no overloads differing only in type arguments. - The compiler inserts casts and generates bridge methods to keep overriding working.
- Heap pollution: raw types or unchecked casts let a wrong element enter a list; the failure appears later as
ClassCastException. - Workaround for runtime type info: pass a
Class<T>token.
تفاصيل المخطط المبدئي
عرض عملي
static <T> T create(Class<T> type) throws Exception {
return type.getDeclaredConstructor().newInstance(); // instead of new T()
}اختبر فهمك
Why does new T() not compile?
أظهر الإجابة
T is erased; the JVM does not know the class at runtime.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.