java foundation --- reflection, regular

Java basics - reflection, regularity

1. Reflection

  • Definition : The JAVA reflection mechanism is that in the running state, for any class (class file), all attributes and methods of this class can be known; for any object, any method and attribute of it can be called; this dynamic The information obtained and the function of dynamically calling object methods are called reflection mechanism of java language.

  • There are three ways to get a bytecode object:

    • 1. Use the getClass() method in the Object class.

      Class clazz=object name.getClass() ;

    • 2. Any data type has a static attribute .class to obtain its corresponding Class object.

      Class clazz=类名.Class;

    • 3. The class can be obtained by simply passing the string name of the given class.

      Class clazz=Class.forName(包名.类名);

  • Get a new instance of the class represented by the Class object

    • Get empty parameter constructor:

      Object obj=Class.newInstance( );

    • Get the specified constructor object:

      Constructor constructor=Class.getConstructor (parameter type.Class,...parameter type.Class);//Get a constructor

      Object obj=constructor.newInstance(pass in actual parameters) ;//Initialize the object through the newInstance method of the constructor object.

  • Get the fields of a Class

    • getField(String name) : Returns a Field object that reflects the specified public member fields of the class or interface represented by this Class object.

    • getDeclaredField(String name) : Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object. ( Accessible private properties )

      • Methods in the Field class:

        • setAccessible(boolean flag) : When accessing private properties, the flag needs to be set to true.

        • set(Object obj, Object value) : Sets the field represented by this Field object on the specified object variable to the specified new value.

        • get(Object obj) : Returns the value of the field represented by this Field on the specified object.

  • Get methods in Class :

    • the first method:

      Method[] methods = Class.getMethods() ;//Get all public methods in the class.

      Method[] methods= Class.getDeclaredMethods() ;//Get all methods in the class, including
      private .

    • The second method:

      Method method = Class.getMethod(String name, parameter type.Class,...parameter type.Class) ;// Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object

  • Example:

    • Person class:
public class Person 
{
    private String name;
    private int age;

    public Person(int age,String name)
    {
        super();
        this.age=age;
        this.name=name;

        System.out.println("Person param run………"+this.name+":"+this.age);
    }
    public Person()
    {
        super();

        System.out.println("Person run");
    }

    public void show()
    {
        System.out.println(name+"……show run……"+age);
    }
    private void privateMethod()
    {
        System.out.println("method run");
    }
    public void paramMethod(String str ,int num)
    {
        System.out.println("paramMethod run……"+str+":"+num);
    }
    public static void staticMethod()
    {
        System.out.println("static method run……");
    }
}
  • Demonstration of the Class method:
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
class ReflectDemo1 
{
    public static void main(String[] args) throws Exception
    {
        String className="Person"; //类的字符串名称

        Class clazz=Class.forName(className);//通过Class类中forName方法获得该类

        Person p=(Person)clazz.newInstance();//调用空参数创建对象

        System.out.println("------------");

        Field field=clazz.getDeclaredField("age");//获取私有字段

        field.setAccessible(true);//对私有字段的访问取消权限检查,暴力访问。

        field.set(p,10);//设置Person对象中的age属性值

        Object o=field.get(p);//获取age的值

        System.out.println("获取的字段信息:"+field);//私有字段信息

        System.out.println("设置的年龄:"+o);

        System.out.println("------------");

        Method method= clazz.getDeclaredMethod("privateMethod",null);//获取私有方法

        method.setAccessible(true);//取消权限检查,暴力访问

        method.invoke(p,null);//运行Person类中privateMethod方法

    }

}
  • Output result:
    write picture description here

2. Regular

  • Features:

    • Regular expressions are used to manipulate string data.

    • manifested by some specific symbols.

  • Summary of Common Constructs of Regular Expressions

    • Character class:

      • [abc] a, b, or c (simple class)

      • [^abc] Any character except a, b, or c (negation)

      • [a-zA-Z] a to z or A to Z inclusive (range)

    • Predefined character classes:

      • \d Digits: [0-9]

      • \D non-digit: [^0-9]

      • \s whitespace character: [ \t\n\x0B\f\r]

      • \S non-whitespace characters: [^\s]

      • \w word character: [a-zA-Z_0-9]

      • \W non-word character: [^\w]

    • Greedy Quantifier:

      • X? X, once or not at all

      • X* X, zero or more times

      • X+X, one or more times

      • X{n} X, exactly n times

      • X{n,} X, at least n times

      • X{n,m} X, at least n times, but not more than m times

    • Boundary matcher:

      • ^ start of line

      • $ end of line

      • \b word boundary

      • \B non-word boundary

      • \A start of input

      • \G end of previous match

      • \Z End of input, used only for final terminator (if any)

      • \z end of input

  • Common functions of regular expressions :

    • match
      • In fact, the matches method in the String class is used.
    • cut
      • In fact, the split method in the String class is used.
    • replace
      • In fact, the replaceAll method in the String class is used.
    • Obtain
      • Encapsulate the regular rules into objects, and associate them with strings through the matcher method of the regular objects.
  • Example:

    • Code:
import java.util.regex.*;
class RegexDemo2 
{
    public static void main(String[] args) 
    {
        functionDemo_1();
        System.out.println("------------");
        functionDemo_2();
        System.out.println("------------");
        functionDemo_3();
        System.out.println("------------");
        functionDemo_4();
    }
    //演示匹配
    public static void functionDemo_1()
    {
        //匹配手机号是否正确
        String tel="13824955439";
        //定义一个正则表达式
        String reg="1[358]\\d{9}";
        boolean b=tel.matches(reg);
        System.out.println(tel+":"+b);
    }
    //演示切割
    public static void functionDemo_2()
    {
        String str="zhaoshan xiaoqiang     liliu";
        //一个或多个空格
        String reg=" +";
        String[] names=str.split(reg);
        for (String name:names )
        {
            System.out.println(name);
        }
    }
    //演示替换
    public static void functionDemo_3()
    {
        String str="13876535946";
        //$1表示前一个参数的第一组,$3表示前一个参数的第三组
        str=str.replaceAll("(\\d{3})(\\d{4})(\\d{4})","$1****$3");
        System.out.println(str);
    }
    //演示获取
    public static void functionDemo_4()
    {
        String str = "da jia hao,ming tian bu fang jia";
         //\\b表示单词边界
        String reg="\\b[a-z]{3}\\b";
        //将正则表达式进行封装成对象
        Pattern p=Pattern.compile(reg);
        //通过正则对象获取匹配器对象
        Matcher m=p.matcher(str);
        //查找:find();
        while (m.find())
        {
            System.out.println(m.group());//获取匹配的子序列
            System.out.println(m.start()+":"+m.end());
        }

    }
}
  • Output result:
    write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325544418&siteId=291194637