[Get class file object in three ways]

Package Test; 

/ ** 
 * @author Shusheng 
 * @description acquired class file object in three ways 
 * @email [email protected] 
 * @date 2018/12/23 23:14 
 * / 
public  class ReflectDemo {
     / * 
     * reflection : file is through the class object to use member variables in this file, constructor, member method. 
     * To use this, you must first get class file object, that is, in fact, been the object Class class. 
     * Class Class: 
     * member variables Field, 
     * Constructor the Constructor 
     * members method Method, 
     * 
     * acquired class file object ways: 
     * A: getClass Object class () method 
     * B: Data type static property class 
     * C: Class category the static method 
     * public static Class forName (String className) 
     * 
     * generally, we in the end who use it?
     * A: Choose one of their own play, the second more convenient 
     * B: The third development 
     * Why because the third is a string, not a specific class name?. So that we can put this string configuration to a configuration file. 
     * / 
    Public  static  void main (String [] args) throws a ClassNotFoundException {
         // mode. 1 
        the Person P = new new the Person (); 
        Class C = p.getClass (); 
        the Person P2 = new new the Person (); 
        Class C2 = p2.getClass (); 
        System.out.println (P == P2); // FALS 
        System.out.println (C == C2); // to true 

        // embodiment 2
        Class c3 = Person.class;
        // int.class;
        // String.class;
        System.out.println(c == c3);

        // 方式3
        // ClassNotFoundException
        Class c4 = Class.forName("day27.Person");
        System.out.println(c == c4);
    }

}



package test;

/**
 * @author shusheng
 * @description
 * @Email [email protected]
 * @date 2018/12/23 23:49
 */
public class Person {
    private String name;
    int age;
    public String address;

    public Person() {
    }

    private Person(String name) {
        this.name = name;
    }

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

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

    public void show() {
        System.out.println("show");
    }

    public void method(String s) {
        System.out.println("method " + s);
    }

    public String getString(String s, int i) {
        return s + "---" + i;
    }

    private void function() {
        System.out.println("function");
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", address="
                + address
                + "]";
    }

}

 

Guess you like

Origin www.cnblogs.com/zuixinxian/p/11275218.html