Loading

Java反射机制示例

链接:

http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html

 

package com.stono.reftest;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Ref {
    @SuppressWarnings("unused")
    public static void main(String[] args) throws Exception {
        // 实例化Class对象;Class是所有类的类;
        Glyph glyph = new Glyph();
        Class<? extends Glyph> class1 = glyph.getClass();
        Class<?> class2 = Glyph.class;
        Class<?> class3;
        class3 = Class.forName("com.stono.reftest.Glyph");
        // 通过Class对象实例化类;必须有无参构造函数
        Glyph glyph2 = class1.newInstance();
        // 通过Class对象获取构造函数;
        Constructor<?>[] constructors = class1.getConstructors();// 长度为1
        // 获取构造函数的Modifier
        int modifiers = constructors[0].getModifiers();
        // 获取Modifier字符串;
        String modifierStr = Modifier.toString(modifiers);
        // 获取构造函数的参数类型;
        Class<?>[] parameterTypes = constructors[0].getParameterTypes();
        // 通过构造函数进行对象构造;
        Glyph glyph3 = (Glyph) constructors[0].newInstance();
        // 获取类的所有接口;
        Class<?>[] interfaces = class3.getInterfaces();
        // 获取类的父类
        Class<?> superclass = class3.getSuperclass();
        // 获取类的所有方法,不会返回构造函数;
        Method[] methods = class3.getMethods();
        // 获取异常类型;Constructor和Method都继承自AccessibleObject
        Class<?>[] exceptionTypes = methods[0].getExceptionTypes();
        Class<?>[] exceptionTypes2 = constructors[0].getExceptionTypes();
        // 获取本地全部属性;包括公共和私有;
        Field[] fields = class3.getDeclaredFields();
        // 取得公共属性;
        Field[] fields2 = class3.getFields();
        // 获取method
        Method m = class3.getMethod("writeGlyph", String.class);
        // 调用method
        m.invoke(class3.newInstance(), "g");
        // 获取某一个属性,可以是私有的;
        Field field = class3.getDeclaredField("name");
        // 设置其访问权限;
        field.setAccessible(true);

    // 获得属性值 参考:http://blog.csdn.net/restraint/article/details/17951453
    Object val = field.get(glyph3);//得到此属性的值 

// 进行属性的设置; field.set(class3.newInstance(), "male"); // 定义数组; int[] iarr = { 1, 2, 3, 4, 5 }; // 获取数组元素的类型; Class<?> componentType = iarr.getClass().getComponentType(); // 获取数组长度; int length = Array.getLength(iarr); // 获取数组第二个元素; Array.get(iarr, 1); // 设置数组第二个元素; Array.set(iarr, 2, 200); // 创建某类型的数组;长度为10; Object newArray = Array.newInstance(componentType, 10); // 进行数组拷贝 System.arraycopy(iarr, 0, newArray, 0, length); } } @SuppressWarnings("unused") class Glyph implements icon { private String name; public Glyph() { } public void writeGlyph(String g) { System.out.println(g); } } interface icon { }

 

posted @ 2015-09-18 17:28  stono  阅读(200)  评论(0编辑  收藏  举报