Java反射简单代码记录

Java反射简单代码记录

看代码就好

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

public class Test{

	public static void main(String[] args) throws Exception {
		Class<?> classFS = Class.forName("FanShe");
		
		/*
		 * Constructor 构造器相关的类
		 */
		
		// 用无参构造方法,创建实例对象
		Object fs = classFS.newInstance();
		// *************有参构造方法
		Constructor<?> constructor = classFS.getConstructor(String.class);
		System.out.println("构造方法:");
		Object object1 = constructor.newInstance("window10");
		// *************

		/*
		 * Field 成员变量相关的类
		 */
		
		// 获取成员变量值
		Field[] declaredFields = classFS.getDeclaredFields();
		for (int i = 0; i < declaredFields.length; i++) {
			Field field = declaredFields[i];
			field.setAccessible(true);
			System.out.println("名字:" + field.getName() + " 类型:" + field.getType() + 
					" 值:" + field.get(fs));
			//field.get(fs)中的get(object obj)传入的需要是创建的出来的实例对象
			//就是用这个返回的object:classFS.newInstance();也可是object1这个实例对象
			
		}

		/*
		 * Method 方法相关的类
		 */
		
		// 获取执行方法
		Method[] declaredMethods = classFS.getDeclaredMethods();
		for (int i = 0; i < declaredMethods.length; i++) {
			Method method = declaredMethods[i];
			System.out.print("方法名:" + method.getName() + " 方法执行:");
			method.invoke(object1);//fs和object1是一样的。
		}
	}

}

class FanShe {
	String s1 = "World!";
	String s2 = "java!";
	private String s3 = "China";

	public FanShe() {
	}

	public FanShe(String s) {
		System.out.println("Hi," + s);
	}

	void helloWorld() {
		System.out.println("hello " + s1);
	}

	void helloJava() {
		System.out.println("hello " + s2);

	}

	void helloChina() {
		System.out.println("hello " + s3);

	}

	void helloWeekend() {
		System.out.println("hello Weekend!");
	}

	void helloLaoWang() {
		System.out.println("hello LaoWang");

	}
}

结果:

构造方法:
Hi,window10
名字:s1 类型:class java.lang.String 值:World!
名字:s2 类型:class java.lang.String 值:java!
名字:s3 类型:class java.lang.String 值:China
方法名:helloChina 方法执行:hello China
方法名:helloJava 方法执行:hello java!
方法名:helloWeekend 方法执行:hello Weekend!
方法名:helloWorld 方法执行:hello World!
方法名:helloLaoWang 方法执行:hello LaoWang

posted on 2020-10-16 20:44  寄居の友人c  阅读(151)  评论(0编辑  收藏  举报