java 高新技术 总结(一)(二)

2014-11-24 03:32:06 · 作者: · 浏览: 4
x"); ff3.setAccessible(true); System.out.println(ff3.get(f1)+""); /** * 利用反射改变值 * 将f1对象中所有的成员变量中含有的a变为b */ Field[] fields = f1.getClass().getFields(); for (Field field: fields) { if (field.getType()==String.class) { String priValue = (String) field.get(f1); String newValue = priValue.replace('a', 'b'); field.set(f1, newValue); } } System.out.println(f1); /** * 获取方法 * 调用方法 */ //new String().charAt(index) Method methodCharat=String.class.getMethod("charAt", int.class); System.out.println(methodCharat.invoke(str2, 1)); //System.out.println(methodCharat.invoke(null, 1));//表明是一个静态方法 } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

利用反射调用其它类的main()方法


class TestArguments{
	public static void main(String[] args){
		for(String arg : args){
			System.out.println(arg);
		}
	}
}


//TestArguments.main(new String[]{"111","222","333"});
		String startingClassName = args[0];
		Method mainMethod = Class.forName(startingClassName).getMethod("main", String[].class);
		//mainMethod.invoke(null, new Object[]{new String[]{"111","222","333"}});
		mainMethod.invoke(null, (Object)new String[]{"111","222","333"});