日期:2014-05-16  浏览次数:20372 次

java反射和JSONArray
package com.company.test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Student {//必须提供get和set方法

public Student(String name, int age) {
// TODO Auto-generated constructor stub
this.nameString = name;
this.age = age;
}

public Student() {}

public void sayHello() {
System.out.println("hello");
}

public String getNameString() {
return nameString;
}
public void setNameString(String nameString) {
this.nameString = nameString;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

String nameString;
int age;

private static void testJson() {
List list = new ArrayList();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i ++) {
Student s = new Student("name_" + i, 10 + i);
list.add(s);
JSONObject jsonObject = JSONObject.fromObject(s);//必须提供get和set方法
jsonArray.add(jsonObject);
//System.out.println(jsonObject);
// System.out.println(jsonObject.getString("name"));
}
//System.out.println(list);
// System.out.println(jsonArray);
System.out.println(list);
jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray);
}

//public static int aa() {
//public static int aa(int a) {
private static int aa(int a) {
return 100;
}

public static void main(String[] args) throws Exception {
//testJson();
//testReflect();
Method method = findMethod(Student.class, "aa");
//System.out.println(method.invoke(Student.class.newInstance(), 11));
System.out.println(method.invoke(Student.class, 11));//静态aa方法可以直接这样
}

private  static void testReflect() throws Exception {
//Class<?> c = Class.forName("com.test.reflect.Student");
Class<?> sClass = Student.class;
Object sObject = sClass.newInstance();
Method sayHello = sClass.getMethod("sayHello", null);
//Object result = sayHello.invoke(sObject, new Object[]{});

//Method aaMethod = sClass.getMethod("aa", null);//无参数
//Object result = aaMethod.invoke(sClass, null);

//Method aaMethod = sClass.getMethod("aa", int.class);//不能写成Integer
//Object result = aaMethod.invoke(sClass, 100);//不能访问私有的
//System.out.println(result);
System.out.println("*************************");

Method[] methods = sClass.getDeclaredMethods();//可以访问私有的
for (Method m : methods) {
// System.out.println(m.getName());
//if (m.getName().equals("aa")) {
if (m.getName() == "aa") {
System.out.println(m.invoke(sObject, 100));
break;
}
}

System.out.println("*************************");
for (Field field : sClass.getDeclaredFields()) {
System.out.println(field.getName());
}
}

private static Method findMethod(Class c, String methodName) {
for (Method m : c.getDeclaredMethods()) {
if (m.getName().equals(methodName))
return m;
}
return null;
}
}