反射基础例子

基本例子
package cn.jasonote;
interface Fruit
{
    void eat();
}
class Apple implements Fruit
{
    @Override
    public void eat(){
        System.out.println("eat apple");
    }
}
class Origin implements Fruit
{
    @Override
    public void eat(){
        System.out.println("eat Origin");
    }
}
class F
{
    public static Fruit getInstance(String className) {
        Fruit f = null;
        try{
            f = (Fruit) Class.forName(className).newInstance();
        }catch(Exception e){}
        return f;
    }
}
public class TestF
{
    public static void main(String[] args) {
        Fruit f = F.getInstance("cn.jasonote.Origin");
        f.eat();
    }
}

代码解释反射

package com.jasonote;
/**
 * Created by Jasonote on 2017/9/14.
 **/
public class Book {
    private String title;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
}
import java.lang.reflect.Method;
public class TestF2 {
    public static void main(String[] args) throws Exception{
        String fieldName = "title";
        Class<?> cls = Class.forName("com.jasonote.Book");
        Object obj = cls.newInstance();
        Method setMet = cls.getMethod("set" + initCap(fieldName), String.class);
        Method getMet = cls.getMethod("get" + initCap(fieldName), String.class);
        setMet.invoke(obj, "Jasonote");
        System.out.println(getMet.invoke(obj));
    }
    public static String initCap(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
}
import java.lang.reflect.Field;
public class TestF3 {
    public static void main(String[] args) throws Exception {
        String fileName = "title";
        Class<?> cls = Class.forName("com.jasonote.Book");
        Object obj = cls.newInstance();
        Field titleField = cls.getDeclaredField(fileName);
        titleField.setAccessible(true);//取消封装
        titleField.set(obj, "Java开发");
        System.out.println(titleField.get(obj));
    }
}

Jason.wang

When you find your talent can't afford to be ambitious, be quiet and study !

You may also like...