当前位置:网站首页>Generics and annotations
Generics and annotations
2022-07-24 05:21:00 【x0757】
Catalog
1. What is generics ?
In fact, when we use collections again, we have used generics List<T> Create a List object List<Student> list=new ArrayList();
<T> It's generics .
The so-called generics are defined in the class , Do not specify data types for properties and methods in the class , Instead, specify the corresponding data type for the class object when it is created .
2. Why use generics ?
Example : It is required to define a Point Point class , The attributes in this class are x Coordinates and y coordinate .
requirement : x and y The values of can all be integer types .
x and y The values of can all be decimal types .
x and y The values of can all be string types .
How to define this class ? How to determine the type of attribute .----Object type
public class Point {
//x coordinate
private Object x;
//y coordinate
private Object y;
// Output the value of coordinates
public void show(){
System.out.println("x coordinate :"+x+";y coordinate :"+y);
}
public Point() {
}
public Point(Object x, Object y) {
this.x = x;
this.y = y;
}
public Object getX() {
return x;
}
public void setX(Object x) {
this.x = x;
}
public Object getY() {
return y;
}
public void setY(Object y) {
this.y = y;
}
}test
public class Test {
public static void main(String[] args) {
Point p1=new Point(10,20);// Coordinates are integers int-- Automatic boxing ->Integer--->Object( Upward transformation )
p1.show();
Point p2=new Point(25.5,36.6);// Coordinates are decimal
p2.show();
Point p3=new Point(" East longitude 180 degree "," North latitude 25 degree ");// The coordinates are string
p3.show();
}
}however : If we assign an integer to the coordinate , An assignment is a string , Will an error be reported at this time .
But it goes against the requirements of our design , This is the data type security problem we mentioned . How to solve the problem of data type security ?
Generics can be used to solve .
public class Point<T> {
//x coordinate ----
private T x;
//y coordinate
private T y;
// Output the value of coordinates
public void show(){
System.out.println("x coordinate :"+x+";y coordinate :"+y);
}
public Point() {
}
public Point(T x, T y) {
this.x = x;
this.y = 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;
}
}
class Test{
public static void main(String[] args) {
Point<Integer> p1=new Point<Integer>(10,20);// Coordinates are integers int-- Automatic boxing ->Integer--->Object( Upward transformation )
p1.show();
Point<Double> p2=new Point<Double>(25.5,36.6);// Coordinates are decimal
p2.show();
Point<String> p3=new Point<String>(" East longitude 180 degree "," North latitude 25 degree ");// The coordinates are string
p3.show();
}
}
Be careful : The generic types above must all be reference types . It can't be the basic type .
Using generics ensures the safety of data types .
3. How to define generics
Generics can be defined on classes , On the interface , On the way . Generic classes , Generic interfaces and generic methods .
Generics can solve the security problem of data types , The main principle is to pass a == Identify the data type of an attribute in the class or the return value and parameter type of a method ==. In this way, when declaring or instantiating a class, you only need to specify the required type .
Format :
public class Class name < Generic flags , Generic flags ....>{
// Members of the class
}
public class Testfx {
public static void main(String[] args) {
Info<String> i1= new Info<>();
i1.setVar(" having dinner ");
i1.show();
Info<Integer> i2= new Info<>();
i2.setVar(10);
i2.show();
// If no generic type is specified, the default is Object,
Info i3 = new Info<>();
i3.setVar("hello");
i3.show();
// If you want to use real type acceptance , Then it must be enforced
String var = (String) i3.getVar();
}
}
//T The logo can be named arbitrarily .----> So when you create an object , You must specify a data type for each generic .
class Info<T>{
public T var;
public void show(){
System.out.println(var);
}
public T getVar() {
return var;
}
public void setVar(T var) {
this.var = var;
}
}4. wildcard
Objects in development == reference == Is the most common , But if in the operation of a generic class , It's going on == When a reference is passed, the generic type must match before it can be passed , Otherwise, it cannot be transmitted ==. If you want to pass , You can define generics as ? wildcard .
public class Testtbf {
public static void main(String[] args) {
Info<Integer> i1 = new Info<>();
i1.setVar(100);
fun(i1);
Info<Double> i2= new Info<>();
i2.setVar(1.2);
fun(i2);
Info<String> i3 = new Info<>();
i3.setVar(" Little Pampa , You're naughty again ");
fun(i3);
}
public static void fun(Info<?> info){
info.show();
}
}
class Info<T>{
private T var;
public void show(){
System.out.println("show===="+var);
}
public Info(T var) {
this.var = var;
}
public Info() {
}
public T getVar() {
return var;
}
public void setVar(T var) {
this.var = var;
}
}5. Restricted generics
In reference passing , In the generic operation, you can also set a generic object == Upper limit of scope == and == Range lower limit ==. The upper limit of the range is used extends Keyword declaration , Indicates that the parameterized type may be the specified type or a subclass of this type , The lower range limit uses super Make a statement , Indicates that the parameterized type may be the specified type or the parent type of this type .
grammar :
[ Set the upper limit ]
Declare objects : Class name <? extends class > Object name ;
Defining classes : [ Access right ] Class name < Generic identity extends class >{}[ Set the lower limit ]
Declare objects : Class name <? super class > Object name ;
Defining classes : [ Access right ] Class name < Generic identity super class >{}
public class TestSxfx {
public static void main(String[] args) {
Info<Number> i = new Info<>();
i.setVar(12);
fun01(i);
fun02(i);
Info<Integer> i2 = new Info<>();
i2.setVar(23);
fun01(i2);
Info<Object> i3 = new Info<>();
i3.setVar(" Little Pampa ");
fun02(i3);
}
// ceiling
public static void fun01(Info<? extends Number> info){
info.show();
}
// Lower limit
public static void fun02(Info<? super Number> info){
info.show();
}
}
class Info<T>{
private T var ;
public void show(){
System.out.println(var);
}
public Info() {
}
public Info(T var) {
this.var = var;
}
public T getVar() {
return var;
}
public void setVar(T var) {
this.var = var;
}
}6. Generic interface
The above examples all use generic classes . And in the jdk1.5 in the future , Generics can also be defined on interfaces , Defining generics for interfaces is similar to defining generic class syntax .
grammar :
public interface The interface name < Generic flags , Generic flags ....>{
// static const
// Abstract method .
}
public class TestInterface {
public static void main(String[] args) {
Upan u= new Upan();
u.eat();
Mouse m = new Mouse();
m.eat();
}
}
interface USB<T>{
T eat();
}
class Upan implements USB<String>{
@Override
public String eat() {
System.out.println("U");
return null;
}
}
class Mouse<T> implements USB<T>{
@Override
public T eat() {
System.out.println("M");
return null;
}
}7. Generic methods
All the generic operations learned earlier are to generize the entire class , But you can also define generic methods in classes . The definition of a generic method has nothing to do with whether the class it belongs to is a generic class , The class can be generic , It can also not be a generic class .
【 A simple definition of generic methods 】
[ Access right ] ==< Generic identity >== Generic identity Method name ( Generic identity Parameter name )
public class TestClass {
public static void main(String[] args) {
String hello = People.fun("hello");
Double fun = People.fun(10.1);
Integer fun1 = People.fun(20);
}
}
class People{
// Generic methods : static Static members , As the class loads, it is loaded into JVM In the memory . Constant pool
public static <T> T fun(T t){
return t;
}
}8 annotation
notes : java Will not compile the contents of comments , Comments for programmers .
annotation : It is a program to see , When the program sees this annotation , It should be parsed .
for example : @Controller @Override
Classification of annotations :
1. Predefined annotations
2. Custom annotation
3. Yuan notes
8.1 Predefined annotations
Predefined annotations are JDK Some self-contained comments , The annotation is JVM And analysis .
1. @Override: Rewritten annotation . Conform to the rewritten rules .
2. @Deprecated: Indicates that it is out of date .
3. @SuppressWarnings: Indicates suppression warning .
4. @FunctionInterface: Representation letter 8.2 Digital interface . Indicates that there is only one abstract method in the interface .
8.2 Custom annotation
grammar :
public @interface Annotation name {
// Annotation Properties
data type Property name () default The default value is ;
}
Use custom annotations :
class Method attribute Add @ Annotation name
data type : Basic types , String type , Enumeration type 【 Constant 】, Annotation type , An array type 【 It must be an array of these types 】
public class Test {
public static void main(String[] args) {
Info i=new Info();
i.name=" Smile ";
i.show();
}
}
// Define the annotation
@interface My{
// Annotation Properties
}
// Using annotations
@My
class Info{
@My
public String name;
@My
public void show(){
System.out.println("show================="+name);
}
}
Be careful : There is no difference between using annotations and not using annotations ?
The annotation itself has no meaning , It can only be parsed , Will give real meaning .
We will use reflection to parse the object annotation later .
image :@Override It has been JVM analysis , So that it has corresponding significance .
@Controller @RequestMapping It has been Spring Framework analysis , So it has corresponding significance .
8.3 Yuan notes
Annotations defined on annotations are called meta annotations .
@Controller It can only be added to classes @Override It can only be added to the method .
The reason is that it uses meta annotation, which can set the location of annotation .
1. @Target(value= You can take the following contents ): Role limits where annotations are used .
/** Indicates that it can act on classes , Interface , enumeration */
TYPE,/** attribute */
FIELD,/** In the ordinary way */
METHOD,/** Method parameter */
PARAMETER,/** In terms of construction method */
CONSTRUCTOR,/** local variable */
LOCAL_VARIABLE2. @Retention: When will the annotation take effect . Default source code java Through those stages .
Source phase --> Bytecode stage ---> Operation phase
/**
* The source code takes effect
*/
SOURCE,/**
* Bytecode takes effect
*/
CLASS,/**
* Run time takes effect .
* stay JVM There is this annotation in memory .
Will be set to be valid at runtime
*/
RUNTIME
3. @Documented When producing API The annotation still exists at the time of document .4. @Inherited Whether to run inherited by subclasses .
public class Testzj {
public static void main(String[] args) {
Info i = new Info();
i.setName(" Smile ");
i.show();
}
}
// Indicates where the annotation can be used
@Target(value ={ElementType.TYPE,ElementType.METHOD})
// Indicates when the annotation takes effect --source--class[ The default bytecode is valid ]---runtime[ Verify when reflecting ]
@Retention(value= RetentionPolicy.RUNTIME)
// Are you generating api The annotation exists when the document
@Documented
// Whether subclasses can inherit the annotation , If the annotation uses the following meta annotation when defining, it can be inherited by subclasses .
@Inherited
@interface My{
String value();
int age() default 15;
String[] hobby() default {" Reading a book "};
}
@My(value = "hello")
class Info{
private String name;
@My(value = "world")
public void show(){
System.out.println("show==="+name);
}
public Info() {
}
public Info(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Info{" +
"name='" + name + '\'' +
'}';
}
}边栏推荐
- 【Pytorch】conv2d torchvision.transforms
- Basic knowledge of MySQL database
- XML schema
- Create and delete databases using databases
- 网NN计算能主机系统资e提供的NTCP
- 支撑复杂的模型群监控、实时告警等t4 文件系统。e
- Do you want to have a robot that can make cartoon avatars in three steps?
- 熊市抄底指南
- c2-随机产生函数种子seed、numpy.random.seed()、tf.random.set_seed学习+转载整理
- Execution sequence of finally and return
猜你喜欢
![Embedded system transplantation [3] - uboot burning and use](/img/36/69daec5f1fe41bd3d0433d60816bba.png)
Embedded system transplantation [3] - uboot burning and use

jdbc封装一个父类减少代码重复

Token of space renewable energy

安装Pytorch+anaconda+cuda+cudnn

【sklearn】RF 交叉验证 袋外数据 参数学习曲线 网格搜索

Mrs +apache Zeppelin makes data analysis more convenient

Heavy! The 2022 China open source development blue book was officially released

postgresql:在Docker中运行PostgreSQL + pgAdmin 4

OSS文件上传

Machine vision learning summary
随机推荐
C table data De duplication
Globally and locally consistent image completion paper notes
FTP file transfer protocol
Un7.23: how to install MySQL on linix?
支撑复杂的模型群监控、实时告警等t4 文件系统。e
【sklearn】数据预处理
Crazy God redis notes 09
Heavy! The 2022 China open source development blue book was officially released
Wang Qing, director of cloud infrastructure software research and development of Intel (China): Intel's technology development and prospects in cloud native
【Pytorch】Dataset_DataLoader
【【【递归】】】
Execution sequence of finally and return
泛型和注解
Embedded system transplantation [3] - uboot burning and use
Recursive cascade network: medical image registration based on unsupervised learning
Echo speaker pairing and operation method
SSH service
Career planning route
Machine vision learning summary
Markov random field: definition, properties, maximum a posteriori probability problem, energy minimization problem