Android 反射接口Interface应用

一般直接使用反射接口的并不多,一般用于辅助反射其他的,或者后面所说的代理.所以下面简单说一下,废话不多说,

步骤如下:

<1> : 新建一个Java工程,工程树如下:



<2> : 接口类IOneplusInterface.java如下:

/**
 * 
 */
package com.oneplus.interfaces;

/**
 * @author zhibao.liu
 * @date 2015-11-19
 * @company : oneplus.Inc
 */
public interface IOneplusInterface {

	void OneInterface();
	void TwoInterface();
	
}

我们在里面声明两个接口.

<2> : OneplusInterfaceImpl.java类中如下:

/**
 * 
 */
package com.oneplus.impl;

import com.oneplus.interfaces.IOneplusInterface;

/**
 * @author zhibao.liu
 * @date 2015-11-19
 * @company : oneplus.Inc
 */
public class OneplusInterfaceImpl implements IOneplusInterface{

	@Override
	public void OneInterface() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void TwoInterface() {
		// TODO Auto-generated method stub
		
	}

}
<3> : 主类中:
private static void OneplusInterfaceX(String packagename){
		
		try {
			Class clazz=Class.forName(packagename);
			
			Class interfaces[]=clazz.getInterfaces();
			
			for(int i=0;i<interfaces.length;i++){
				
				Method[] methods=interfaces[i].getMethods();
				for(int j=0;j<methods.length;j++){
					
					System.out.println("Interface Method Name : "+methods[j].getName());
					
				}
				
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


运行一下:

在上面做一个测试中,我们在再OneplusInterfaceImpl类中继续增加两个非接口的方法:

private void ThreeInterfaceImpl(){
		
	}
	
	private void FourInterfaceImpl(){
		
	}

然后再运行:

结果还是一样的,但是如果我们再在主类中增加获取所有方法如下:

Method methods[]=clazz.getDeclaredMethods();
			for(int i=0;i<methods.length;i++){
				
				System.out.println("Method Name : "+methods[i].getName());
				
			}


结果如下:


如果再新建一个IOneplusInterfaces.java,程序如下 :

/**
 * 
 */
package com.oneplus.interfaces;

/**
 * @author zhibao.liu
 * @date 2015-11-20
 * @company : oneplus.Inc
 */
public interface IOneplusInterfaces extends IOneplusInterface {

	void OneplusFunctionOne();
	void OneplusFunctionTwo();
	
}


再让OneplusInterfaceImpl 也实现IOneplusInterfaces这个接口,如下 :

public classOneplusInterfaceImpl implements IOneplusInterface, IOneplusInterfaces

 

运行结果:



直接一般没有直接反射出来使用,进一步应用参考后面的代理的使用.











你可能感兴趣的:(Android 反射接口Interface应用)