java反射样例

没时间解释,先上代码,改日再编辑
package test;

import java.lang.reflect.Method;

class Foo {
	public String fool(String[] say) {
		for (String i : say)
			System.out.println("I want to say :" + i);
		return "success";
	}
}

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("main started...");
		try {
			Class<Foo> c = Foo.class;
			System.out.println("c = " + c);
			Object invoker = c.newInstance();
			System.out.println("invoker = " + invoker.getClass());
			Method m = c.getMethod("fool", new Class[] { String[].class });
			System.out.println(m.invoke(invoker, new Object[] { new String[]{"1", "2", "3"} }));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}



	public String getInsertSql(String tableName) {
		String insertSql = "";
		String column = "";
		String value = "";
		try {
			Class c = this.getClass();
			Method m;
			Field[] fields = c.getDeclaredFields();
			for (Field f : fields) {
				column += f.getName();
				m = c.getMethod("get"
						+ f.getName().substring(0, 1).toUpperCase()
						+ f.getName().substring(1), null);
				value += m.invoke(this, null);
			}
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println(column + value);
		return insertSql;
	}

你可能感兴趣的:(java,reflect)