---
title: "反射备忘"
author: "wiseideal"
date: "2014-04-16T15:08:47Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-04-16T15:08:47Z"
id: 2047370
url: "https://wiseideal.iteye.com/blog/2047370"
---

public class TestMain {

 

/\**

\* @param args

\*/

public static void main(String\[] args) {

WorkMate mate = new WorkMate();

try {

Class mateClass = mate.getClass();

for(Field field : mateClass.getDeclaredFields()){

System.out.println(field.getName());

}

Field field =  mate.getClass().getDeclaredField("thisName");

field.setAccessible(true);

field.set(mate, "wiseideal");

Class\[] parameterTypes = new Class\[1];

parameterTypes\[0] = String.class;

mate.getClass().getDeclaredMethod("sayHei", parameterTypes).invoke(mate, "What's Up");

} catch (IllegalArgumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SecurityException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (NoSuchFieldException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (NoSuchMethodException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

 

}

 

static class WorkMate{

String thisName = "chaos";

public void sayHei(String msg){

System.out.println(thisName+" said : "+msg);

}

}

 

}