JAVA 反射机制简单运用

一切操作都是将使用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;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值