1. 程式人生 > >java反射基礎應用備註

java反射基礎應用備註

class AI lac pac true row 暴力 基礎應用 tcl

反射機制應用很廣泛。這裏簡單備註下

package com.shone.ailin;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Reflectdemo {
    
    public static void main(String[] args) throws Exception {
        
        
        printVar();
        
        createInstance();

        printAllVarName();
        
    }
    
    
//打印所有成員變量名 private static void printAllVarName() { // TODO Auto-generated method stub Point p = new Point(1,3); Field[] fields = p.getClass().getDeclaredFields(); for(int i=0;i<fields.length;i++) { System.out.println("var["+i+"]="+fields[i].getName()); } }
//打印成員變量的值 private static void printVar() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Point p = new Point(1,4); Field fX = p.getClass().getDeclaredField("x"); fX.setAccessible(true); //這裏必須要加上 。不然會拋出異常。因為是私有成員變量,所以,需要暴力的反射
int x = (int)fX.get(p); System.out.println("x="+x); } //創建實例化對象並調用方法 private static void createInstance() throws Exception, SecurityException { Constructor<Point> con = Point.class.getConstructor(int.class,int.class); try { Point instance = con.newInstance(1,3); Method m = instance.getClass().getDeclaredMethod("addCount", int.class,int.class); m.setAccessible(true); try { int count = (int) m.invoke(instance,2,7); System.out.println(count); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } }

Point類

package com.shone.ailin;

public class Point {
    private int x ;
    public int y ;
    
    public Point(int x ,int y ) {
        // TODO Auto-generated constructor stub
        super();
        this.x = x;
        this.y = y;
    }
    
    private int addCount(int x,int y) {
        return x+y;
    }

}

java反射基礎應用備註