Java反射基础用法

基本用法(类调用):

//获取系统属性值反射方法
public String getSystemProperty(String key) {
	String v = "";
	try {
		Class<?> c = Class.forName("android.os.SystemProperties");
		Method m = c.getDeclaredMethod("get", String.class);
		v = (String) m.invoke(c, key);
	} catch (Exception e) {}
	if ("".equals(v)) return "no";
	return v.trim();
}


基本用法(实例调用):

    public List<String> getxxApps() {
        List<String> apps = new ArrayList<String>();
        try {
            Class<?> cl = Class.forName("com.android.xx.cl");
            Object con = cl.newInstance();
            Method myMethod = cl.getMethod("myMethod",
                    null);
            apps = (List<String>) myMethod.invoke(con, null);
            
        } catch (ClassNotFoundException 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 (NoSuchMethodException 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();
        }        
        return apps;
    }

猜你喜欢

转载自blog.csdn.net/lgglkk/article/details/78266758
今日推荐