Java反射プライベート属性とメソッドの取得

11826 ワード

Studioクラス:

//                 ,       :"  ",      eat       :      
//
//	public class Student{
//		
//		private Student(){}
//		private String name;
//		
//		private void eat(String food){
//			System.out.print(name+" "+food);
//		}
//			
//		
//	}
package com.n4;

public class Student {
	private Student() {
	}

	private String name;

	private void eat(String food) {
		System.out.println(name + " " + food);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Student(String name) {
		super();
		this.name = name;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


Testクラス
package com.n4;

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

public class Test {

	public static void main(String[] args)
			throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchFieldException {
		// TODO Auto-generated method stub
//		Class> clazz=Class.forName("com.n4.Student");
//		Method method=clazz.getDeclaredMethod("",String.class);
//		method.setAccessible(true);
//		System.out.println(method.toGenericString());
//		Object object=method.invoke(clazz.newInstance(), "   ");
//		System.out.println(object);

//		Class clazz=Class.forName("com.n4.Student");
//		Object stu=clazz.newInstance();
//		
//		java.lang.reflect.Field f=clazz.getField("name");
//		
//		
//		f.set(stu,"   ");
//		f.setAccessible(true);
//		
//		Object name=f.get(stu);
//		
//		System.out.println(name);

//		//           
//		Class class1=Class.forName("com.n4.Student");
//		//       
//		Object stuObject=class1.newInstance();
//		
//		//           
//		Method method=class1.getMethod("setName");
//		Object object=method.invoke(stuObject);
//		System.out.println(object);

//		//       
//		Class class1=Class.forName("com.n4.Student");
//		//      
//		Object stuObject=class1.newInstance();
//		//        
//		Method method=class1.getDeclaredMethod("setName");
//		// jvm     
//		method.setAccessible(true);
//		//    
//		method.invoke(stuObject, "    ");

		Class<Student> class1 = Student.class;

		Constructor c = class1.getDeclaredConstructor();

		c.setAccessible(true);
		Student student = (Student) c.newInstance();

		java.lang.reflect.Field m = class1.getDeclaredField("name");
		m.setAccessible(true);
		m.set(student, "   ");

		Method method = class1.getDeclaredMethod("eat", String.class);

		method.setAccessible(true);
		method.invoke(student, "  ");
	}

}