Generic reflection annotation

1. Generics

1.1 generic definitions

      Pass the data type of a class / interface / method / variable to the class / interface / method / variable like using parameters.

      Parameterization and arbitrariness of data types.

1.2 why do you need generics?

      first day   int is required for x,y variables in class

      public  class  Test1{

            private  int x;

            private  int y;

      }

      the second day   The X and Y variables in the class need double. We created a new class and modified the data type of X and Y variables

      public  class  Test2{

            private  double x;

            private  double y;

      }

      on the third day   The X and Y variables in the class need String. We created a new class and modified the data type of X and Y variables

      public  class  Test3{

            private  String x;

            private  String y;

      }

      the forth day   The X and Y variables in the class need char. We created a new class and modified the data type of X and Y variables

      ......

      When we need many java classes with similar business logic but different data types, we don't want to create multiple java classes with similar business logic but different data types.

      We wonder if we can use one class to unify multiple java classes with similar business logic but different data types

      To solve this problem, we will first deal with the unification of data types. To deal with the unification of data types, we will think of the java.lang.Object class.

public class ObjectTest {

      private  Object  x;

      private  Object  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;

      }

      }



      ObjectTest  o=new ObjectTest();

      //o.setX(180);

      //o.setY(36);

      //Change the x,y variables to String

      o.setX("one hundred and eighty");

      o.setY("Thirty-six");

      System.out.println(o.getX()+","+o.getY());

      //Type conversion

      // java.lang.ClassCastException

      int sum=(Integer)(o.getX())+(Integer)(o.getY());

      System.out.println(sum);

     

      Although we can use Object to unify data types, we need to cast when using it

      If the conversion is improper, a type conversion exception java.lang.ClassCastException will appear.

      At this time, we will wonder whether we can pass the data type to the java class we need to use like parameters, which requires us to unify the type and avoid forced type conversion.

      Generics are studied to solve the above problems.

1.3 how to create a generic class / generic interface

When creating a class, add a "< >" after the class name and a single uppercase letter to "< >" to receive a specific data type.

      ”<>” A single uppercase letter in can appear more than one, separated by ",".

      The part of the class that needs data type can be replaced by a single uppercase letter. When we create the class, we can pass the specific data type to a single uppercase letter. All the parts of the class that need data type will become the specific data type we pass.

public class Test1<I,S> {

      private  I  x;

      private  S  y;

     

      public I getX() {

            return x;

      }

      public void setX(I x) {

            this.x = x;

      }

      public S getY() {

            return y;

      }

      public void setY(S y) {

            this.y = y;

      }

}



public static void main(String[] args) {

            Test1<Integer,String>  t1=new Test1<Integer,String>();

            t1.setX(180);

            int x=t1.getX();

            t1.setY("Thirty-six");

            String  y=t1.getY();

      }

1.4 how to use generic classes / interfaces?

Generally, we rarely create generic related elements. We often use generic classes / interfaces in the development package provided by jdk.

      1. When creating objects with generic classes, you need to pass specific data types

            Test1   t1=new Test1(); // If it is illegal, a warning message will be generated

            Test1<Integer,String>   t1=new Test1<Integer,String>(); // correct

      2. When a basic data type is used as a generic data type, it is not allowed. Instead, the encapsulation type corresponding to the basic type can be used

            Test1<int,String>   t1=new Test1<int,String>(); // error

            Test1<Integer,String>   t1=new Test1<Integer,String>();// correct

      3. When we create a generic Object, we do not pass the specified data type. The default is Object type. It is accompanied by a warning message     

  public static void main(String[] args) {

            Student stu1=new Student(1001,"zhangsan");

            Student stu2=new Student(1002,"lisi");

            Student stu3=new Student(1003,"wangwu");

            List  stulist=new ArrayList();

            stulist.add(stu1);

            stulist.add(stu2);

            stulist.add(stu3);

            for(Object  obj:stulist){

                  Student  stu=(Student)obj;

                  System.out.println(stu.getStuid()+","+stu.getStuname());

            }

      }

The classes learned before are actually generic classes

java.util Class ArrayList<E>

java.util Class HashMap<K,V>

java.util Class Hashtable<K,V>

The interface learned before is actually a generic interface

java.util Interface Map<K,V>

public interface List<E>

public interface Collection<E>

2. Reflection

2.1 definition and function of reflection

      In the process of program running, we can get the object of a class and call any variable and method in a class. This dynamic process of obtaining information is reflection.

      Function: when we haven't seen a class, we can get all the method and variable information of the whole class only by a complete class name [package name + class name], such as access class name, access restriction modifier, return value, exception type, parameters, etc., but we can't get it in the method body.

      Usage scenario of reflection:

       1. jdbc loading database driver

      2. web.xml configuration of Servlet

      3. Spring framework

2.2 conversion between instance object and reflection object

Reflection object: the object of the class obtained through the reflection mechanism. The reflection object is an object of class type. [note the difference between class Keywords]

Class --- keyword to create a class

Class --- the class name of the class. The created class object is a reflection object.

public final class Class<T>

      Instance object: at present, we have learned that there are three ways to obtain the instance object of a class (new, static method, reflection).

      (1) Get reflected objects from instance objects

      Get the reflection object corresponding to the current instance object through getClass() of the instance object

Through Class class forname (Class name [package name + Class name])

      (2) Get instance objects by reflecting objects

The newInstance() method of the reflection object can get the instance object

package com.weiwei.test1;

public class Main {

   public static void main(String[] args) throws Exception{

   /*

   //There are two ways to get reflected objects

      // 1.Get reflected objects from instance objects

      Student stu=new Student();//Get instance object

      Class classstu1 = stu.getClass();//Get reflected object

      //2.Through Class class forname (Class name [package name + Class name])

      Class classstu2 = Class.forName("com.weiwei.test1.Student");

   */

     

   //Get instance objects by reflecting objects

      //The newInstance() method of the reflection object can get the instance object

      Class classstu2 = Class.forName("com.weiwei.test1.Student");

      Student student=(Student)classstu2.newInstance();

   }

}

2.3 get the complete structure of the class by reflecting the object

Constructor<?>[ ] getConstructors()

Get the construction method

Field[ ] getDeclaredFields()

Get member variables

Method[ ]  getDeclaredMethods()

Get member method

Class<?>[ ]      getInterfaces()

Get interface

Class<? super T>   getSuperclass()

Get parent class

Package    getPackage()

Get package object

int getModifiers()

toString(int) of Modifier   mod)

Java language modifier

Return string

String  getName()

Get class name

[note] the array returned in the above method indicates that there will be multiple arrays, which need to be traversed

Example: get the following information

package com.weiwei.test2;

public class Student extends Person implements MyInter,MyInte{

   private int stuid;

   private String stuname; 

   public Student(){

     

   }

   public String getInfo()throws Exception{    

     

      return "";     

   }

}

Test class:

package com.weiwei.test2;

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.lang.reflect.Modifier;



public class Main {



   public static void main(String[] args) throws Exception{

      //Get reflected object

      Class stuclass = Class.forName("com.weiwei.test2.Student");

          //Get package object

          Package package1 = stuclass.getPackage();

          //Get package name

          String packname = package1.getName();

          System.out.println("package"+"\t"+packname);

         

          //Get the access restriction modifier of the class

          String modifier = Modifier.toString(stuclass.getModifiers());

          //System.out.println(modifier);//public

         

          //Get the name of the class

          //String classname1 = stuclass.getName();

         //System.out.println(classname);//com.weiwei.test2.Student

             //The obtained class name has a package name, so you need to use string operation class interception to create a new method

          String classname = className(stuclass.getName());

          //System.out.println(classname);//Student

         

          //Get the parent object and parent name

          Class superclass = stuclass.getSuperclass();

          String supername = className(superclass.getName());//Person

         

          //Get interface object and interface name

          Class interfaces[] = stuclass.getInterfaces();//Get array

          //System.out.println(interfaces.length);//2   

          String interface1=className(interfaces[0].getName());

          String interface2=className(interfaces[1].getName());

          //Complete structure of output class

          System.out.println(modifier+" "+"class"+" "+classname+" "+"extends"

                +" "+supername+" "+"implements"+" "+interface1+","+interface2+"{");

         

          //Get member variables

          Field[] fields = stuclass.getDeclaredFields();

             //Traversal array

             for(Field field:fields){

                String fieldmodifier = Modifier.toString(field.getModifiers());

                String fieldtypeName = className(field.getType().getName());

                String fieldname = field.getName();

                System.out.println("\t"+fieldmodifier+" "+fieldtypeName+" "+fieldname+";");

             }

            

          //Get the construction method

          Constructor[] constructors = stuclass.getConstructors();

          Constructor constructor = constructors[0];

          String conmodifier = Modifier.toString(constructor.getModifiers());

          String conname = className(constructor.getName());

          System.out.println("\t"+conmodifier+" "+conname+"()"+"{}");

         

          //Get example method

          Method[] methods = stuclass.getDeclaredMethods();

          Method method = methods[0];

          String methodmodifier = Modifier.toString(method.getModifiers());

          String methodreturn = className(method.getReturnType().getName());

          String methodname = method.getName();

          String exname = className(method.getExceptionTypes()[0].getName());

          System.out.println("\t"+methodmodifier+" "+methodreturn+" "+methodname+"()throws"+" "+exname+"{"+"\n\treturn xxx"+"\n\t}");

          System.out.println("}");

   }    

   /**

    * Get class name without package name

    *

    */

   public static String className(String classname){

      return classname.substring(classname.lastIndexOf(".")+1);

   }

}

Output:

 

3. Notes

      Note --- the text used to explain the meaning of the code

      Annotation --- mark the code that explains the function

1.@Override   Judge whether the method rewriting is correct

package com.weiwei.test2;



public class Son extends Person{

  

   //Override the method of the parent class. Obviously, the method of the parent class is getinfo();

   //Obviously, the purpose is to rewrite the method, but it is written as the subclass's own method, but it will not report an error

   /*public void getInfo(){

      System.out.println("Override the method of the parent class' ');

   }

   */

   //Therefore, you need to use annotations to help yourself. If they are inconsistent, errors will be reported

   @Override

   public void getinfo(){

      System.out.println("Override the method of the parent class");

   }

}

2.@SuppressWarnings   Suppress warning messages

      There are parameters --- the reason for the warning

      Location:

  1. Above the current code, only the warning information on the current code is suppressed
  2. Above the method code, only the same type of warning information in the current method is suppressed
  3. Class, only the warning information of the same type in the current class is suppressed

   @SuppressWarnings({ "unused", "rawtypes" })

import java.util.ArrayList;

import java.util.List;



@SuppressWarnings({ "unused", "rawtypes" })

public class Main {



   //@SuppressWarnings({ "unused", "rawtypes" })

   public static void main(String[] args) {

     

   /*

    * @SuppressWarnings("unused")

      Person per=new Person();

      @SuppressWarnings("rawtypes")

      List list=new ArrayList();

      */

      Person per=new Person();

      List list=new ArrayList();

   }



   public void test(){

      Person per=new Person();

      List list=new ArrayList();

   }

}

3. @Deprecated   Identify variable / method / class / interface, obsolete.

      Obsolete elements should be avoided as far as possible because of potential errors

Keywords: Java linq p2p

Added by rekha on Tue, 07 Dec 2021 00:37:48 +0200