当前位置:网站首页>Generics and reflection, this is enough
Generics and reflection, this is enough
2022-07-02 22:59:00 【Xiaopucai learns Java】
Catalog
Generic : A means of checking whether there are errors in the program at the compilation stage .
* Definition of a generic class :
* Benefits of using generics :
Limitations and rules of generics
1, Common methods of using generic parameters :
2, Generic methods that use generics for both return values and parameters
Two ,?super Number, Set the lower bound of the generic
3、 ... and ,? extents Number, Set the Generic upper limit
1, Get the class object ( Yes JVM produce , Globally unique )
2, Get the construction method through reflection .
adopt Method The way to get it , Calling method .
Generic : A means of checking whether there are errors in the program at the compilation stage .
* Definition of generics
The so-called generics are ambiguous types when defining classes , Specify the type when using
Generic :“<>” Use diamond operator ,< class >

* Definition of a generic class :
package Generic ;
public class Point<T> {
//T Type parameter
// here xy The type of is uncertain , But it's guaranteed xy Type consistency of ,xy The type of is determined when the object is generated
private T x;
private T y;
public T getX() {
return x;
}
public void setX(T x) {
this.x = x;
}
public T getY() {
return y;
}
public void setY(T y) {
this.y = y;
}
}
* Use generic classes :
Define generic parameters as String type , take T x convert to String x, In giving x An error will be reported when an integer value is assigned .

Use of multiple generics : Use different capital letters to specify different types .


* Benefits of using generics :
1, The compilation phase checks whether the types are consistent , Avoid the error problem of downcast casts .
2, Code is conducive to reuse .
Limitations and rules of generics
- Type parameters of generic types can only be reference types , Cannot use value type .
- A generic type can have more than one type parameter .
- Generic classes are not real classes , Out of commission instanceof Operator .
- Type parameters of generic classes cannot be used in static declarations .
- If generics are defined , No specific type is specified , The generic type is specified as Ojbect type .
- Generics use ? As a type wildcard , Indicates an unknown type , Can match any type . Because it's unknown , So you can't add elements .
- Type wildcard upper limit :<? extends T>,? Representative is T The type itself or T Subtypes of . Commonly used in generic methods , Avoid type conversion .
- Type wildcard lower limit .<? super T>,? representative T The type itself or T The father type of .
- In addition to wildcards, restrictions can be implemented , class 、 Generic parameters defined in interfaces and methods can also limit upper and lower limits .
** Generic methods :
1, Common methods of using generic parameters :
public T fun(T t){
return t;
}2, Generic methods that use generics for both return values and parameters
public <T> T Point(T t){
return t;
}
If a class is a generic class , The type parameters of generic methods are independent of the generic parameters of classes . Only related to generic parameters defined by your own method .
One class is a general class , Still, generic methods can be defined . But defined generic methods , Can't be static Embellished , Because use static Modified class method , Cannot pass generic parameters to a generic .
Generic methods of generic classes can only be instantiated . Generic methods when defining generic , Use different capital letters , Avoid ambiguity .

Methods using generic parameters , Cannot be defined as static

Generic interface :
Generic interface , Use <> Diamond operator defined interface , When implementing an interface , You can keep generics , It can also be in the implementation class


wildcard :
All three wildcards can be set in classes and methods .
One ,?



Two ,?super Number, Set the lower bound of the generic



3、 ... and ,? extents Number, Set the Generic upper limit
The topmost type can only be Number and Number Subclasses of classes .



** Type Erasure
Generic : Grammatical sugar
Type Erasure : Generic information is actually only in the compilation stage , Get into JVM after , All information related to generics will be erased .
If no Generic upper limit is specified , Then all generic information will be erased as Object type ,
If a Generic upper limit is specified , Then erase to the corresponding generic upper limit type .
Generic classes and ordinary classes enter JVM after , It doesn't make any difference
after javac After compilation , Generate *.class file , Generics will disappear .


Reflection : The mechanism of dynamically obtaining information and calling objects is called reflection mechanism .
The foundation of all frameworks
stay JVM Runtime ,
about JVM Any of the classes in , Can dynamically obtain all properties and methods of this class .
about JVM Any object in , Can dynamically obtain the properties and methods of the object .
The type of reflection :
Runtime type :RTTI
Compile time type :
Person p = new Student();// Compile time type is Person, The runtime type is Student;
The runtime type can be obtained through reflection .

1, Get the class object ( Yes JVM produce , Globally unique )
a, call Class.forName( Package name . Class name )
b, Call class name .class obtain
c, Through object .getClass() obtain .
2, Get the construction method through reflection .
![]()
get Can only get public The attributes and methods of decoration .
getDeclared...() Get all properties and methods .




Break encapsulation :

![]()
Use class keyword , Including arrays , Generated after interface compilation class The file only corresponds to one Class object , This object has JVM produce , Using this object, you can get all the information of this class .
![]()




![]()

adopt Method The way to get it , Calling method .



边栏推荐
- Array advanced improvement
- [羊城杯2020]easyphp
- Higher order operation of bits
- P1007 独木桥
- 牛客网:最大子矩阵
- What is the'function'keyword used in some bash scripts- What is the 'function' keyword used in some bash scripts?
- 位的高阶运算
- [error record] the flutter reports an error (could not read script 'xxx\flutter\u tools\gradle\app\u plugin\u loader.gradle')
- Jerry's built-in short press and long press, no matter how long it is, it is a short press [chapter]
- 'when to use const char * and when to use const char []' - when to use const char * and when to use const char []
猜你喜欢

百度智能云-创建人脸识别应用

小鹏P7出事故,安全气囊未弹出,这正常吗?

大话云原生之负载均衡篇-小饭馆客流量变大了

Qt QSplitter拆分器

Kubernetes uses the host name to allocate the pod on the specified node

Addition, deletion, modification and query of handwritten ORM (object relationship mapping)

World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection

地方经销商玩转社区团购模式,百万运营分享

数据分析学习记录--用EXCEL完成简单的单因素方差分析

Wait to solve the zombie process
随机推荐
MySQL reset password, forget password, reset root password, reset MySQL password
成功改变splunk 默认URL root path
odoo13搭建医院HRP环境(详细步骤)
Hanging mirror security won four global infosec awards on rsac2022
boot actuator - prometheus使用
电商系统微服务架构
[error record] the flutter reports an error (could not read script 'xxx\flutter\u tools\gradle\app\u plugin\u loader.gradle')
[leetcode] number of palindromes [9]
Analyse des données dossiers d'apprentissage - - analyse simple de la variance à facteur unique avec Excel
[NPUCTF2020]ezlogin xPATH注入
[LeetCode] 存在重复元素【217】
Graphic view frame
数据分析学习记录--用EXCEL完成简单的单因素方差分析
Odoo13 build a hospital HRP environment (detailed steps)
【板栗糖GIS】arcmap—为什么使用自定义捕捉的时候,经典捕捉的勾要去掉呢?
图形视图框架
Baidu AI Cloud - create a face recognition application
杰理之快速触摸不响应问题【篇】
Data analysis learning records -- complete a simple one-way ANOVA with Excel
Wait to solve the zombie process