码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA反映练手

时间:2017-04-18 09:30:53      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:arraylist   img   java   throwable   span   exce   row   err   array   

import java.util.List;
import java.util.ArrayList;
import java.lang.reflect.Method;
import java.lang.reflect.Field;

class S {
    private String name;
    private int age;
    
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
}

public class RefTest {  
    public static void main(String[] args) {  
        try {
            Class cls = Class.forName("S");
            boolean b1 = cls.isInstance(new Integer(37));
            System.out.println(b1);
            boolean b2 = cls.isInstance(new S());
            System.out.println(b2);
        } catch (Throwable e) {
            System.err.println(e);
        }
        
        try {
            Class cls = Class.forName("S");
            getProperty(cls);
        } catch (Throwable e) {
            System.err.println(e);
        }
        
        try {
            Class cls = Class.forName("S");
            getMethods(cls);
        } catch (Throwable e) {
            System.err.println(e);
        }
        
    }  
    
    public static Field[] getProperty(Class ownerClass) throws Exception {
        Field[] fields = ownerClass.getDeclaredFields();
        
        for (int i=0; i<fields.length; i++) {
            System.out.println("Property: " + fields[i]);
        }
        
        return fields;
    }
    
    public static Method[] getMethods(Class ownerClass) throws Exception {
        Method[] methods = ownerClass.getDeclaredMethods();
        
        for (int i=0; i<methods.length; i++) {
            System.out.println("Method: " + methods[i]);
        }
        
        return methods;
    }
} 

技术分享

JAVA反映练手

标签:arraylist   img   java   throwable   span   exce   row   err   array   

原文地址:http://www.cnblogs.com/aguncn/p/6726075.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!