1. 程式人生 > >【java反射】Class類型的相關操作演練

【java反射】Class類型的相關操作演練

div gif display 演練 esp arguments 接口 hid col

【一】獲取範型接口的實現類的範型類型

(1)範型接口

技術分享
package org.springframework.context;

import java.util.EventListener;


public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

    /**
     * Handle an application event.
     * @param event the event to respond to
     */
    void onApplicationEvent(E event);

}
View Code

(2)範型接口實現類

技術分享
package com.mobile.thinks.login.listen;

import org.springframework.context.ApplicationListener;

import com.mobile.thinks.login.event.BaseEvent;

public class LoginListen implements ApplicationListener<BaseEvent>{

    @Override
    public void onApplicationEvent(BaseEvent event) {
    
        
    }

    
}
View Code

(3)範型接口實現類的範型的填充類

技術分享
package com.mobile.thinks.login.event;

import org.springframework.context.ApplicationEvent;

public abstract class BaseEvent extends ApplicationEvent {

    public BaseEvent(Object source) {
        super(source);
    }

    
}
View Code

(4)獲取範型的填充類的類型

技術分享
    public static
void main(String[] args) { LoginListen listen=new LoginListen(); Class<?> cls =listen.getClass(); //cls==>class com.mobile.thinks.login.listen.LoginListen System.out.println("cls==>"+cls); Type[] type=cls.getGenericInterfaces(); Type types=cls.getGenericSuperclass(); for(int i=0;i<type.length;i++){ Type ty=type[i]; if(ty instanceof ParameterizedType){ Type[] sTypes=((ParameterizedType)ty).getActualTypeArguments(); for(int j=0;j<sTypes.length;j++){ Type clsa=sTypes[j]; //範型類型==>class com.mobile.thinks.login.event.BaseEvent System.out.println("範型類型==>"+(Class)clsa); } } } }
View Code

【java反射】Class類型的相關操作演練