JAVA 反射机制简单运用

来源:互联网 发布:linux 卸载chromium 编辑:程序博客网 时间:2024/05/17 04:19

一切操作都是将使用Object完成,类、数组的引用都是用Object接收

public final class Class

Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

Method Summary

Class

e.g

package 反射;import java.io.ObjectInputStream.GetField;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class fanshe {    public static void main(String[] args) throws Throwable, SecurityException {        Student st = new Student();        // System.out.println(st.getClass());        // System.out.println(st.getClass().getName());        Class<Student> cl = (Class<Student>) Class.forName("反射.Student");        // Constructor[] con = cl.getConstructors();        // for (int i = 0; i < con.length; i++) {        // System.out.println(con[i].toGenericString());        // }        // Field[] fields = cl.getFields();        // System.out.println(fields.length);        // for (int i = 0; i < fields.length; i++) {        // System.out.println(fields[i].getName());        // System.out.println(fields[i].toString());        // }        // Method[] me = cl.getMethods();        // for (int i = 0; i < me.length; i++) {        // System.out.println(me[i].toString());        // }        Student student = cl.newInstance();        System.out.println(student.name);    }}class Student {    public String name = "lihua";    public String school = "songxiao";    public Integer age = new Integer(24);    public String sex;    public Student() {    }    public Student(String name, String school, Integer age) {        this.name = name;        this.school = school;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSchool() {        return school;    }    public void setSchool(String school) {        this.school = school;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }}
0 0
原创粉丝点击