如何获取类名

anel 2018-03-19 09:24:59
public class Http{
}
public interface HttpHandle<T> {
}

public static void main(String[] args) {
HttpHandle handle = new HttpHandle<Http>(){
};

debug(handle);
}

static void debug(HttpHandle handle){
// 在这里如何获得类名"Http" ?
}
...全文
358 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
maradona1984 2018-03-20
  • 打赏
  • 举报
回复
刚那个代码是获取父类的,你这个是接口,这个亲测可用

package com.wu.passport.sdk.auth;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Test {

	public interface HttpHandle<T> {

	}

	public class Http {

	}

	public static void main(String[] args) {
		HttpHandle<Http> handle = new HttpHandle<Http>() {
		};

		debug(handle);
	}

	static void debug(HttpHandle<?> handle) {
		Class<?> clazz = getClassType(handle, 0,0);
		System.out.println(clazz.getName());
	}

	private static Class<?> getClassType(HttpHandle<?> handle, int pos1,int pos2) {
		Type[] types = handle.getClass().getGenericInterfaces();
		if(types == null || types.length <= pos1){
			return null;
		}
		Type type = types[pos1];
		if (type instanceof ParameterizedType) {
			ParameterizedType parameterizedType = (ParameterizedType) type;
			Type[] genericTypes = parameterizedType.getActualTypeArguments();
			if (genericTypes.length >= pos2 + 1) {
				return (Class<?>) genericTypes[pos2];
			}
		}
		return null;
	}

}

maradona1984 2018-03-20
  • 打赏
  • 举报
回复
引用 3 楼 anel 的回复:
1楼是写死的,不可取 2楼返却回null,不知哪里出问题。
断点看看呗,或者能告知jdk版本和其他运行环境么?比如这个代码是哪个版本编译的,是jar?还是其他
anel 2018-03-20
  • 打赏
  • 举报
回复
1楼是写死的,不可取 2楼返却回null,不知哪里出问题。
maradona1984 2018-03-19
  • 打赏
  • 举报
回复
获取对象的泛型类型么? pos是泛型所在下标,你只有一个写0就可以咯,你的方法是静态方法,把this换成handle对象

	/**
	 * 获取泛型Class信息
	 * 
	 * @return
	 */
	private Class<?> getClassType(int pos) {
		Type type = this.getClass().getGenericSuperclass();
		if (type instanceof ParameterizedType) {
			ParameterizedType parameterizedType = (ParameterizedType) type;
			Type[] genericTypes = parameterizedType.getActualTypeArguments();
			if (genericTypes.length >= pos + 1) {
				return (Class<?>) genericTypes[pos];
			}
		}
		return null;
	}
dong_19890208 2018-03-19
  • 打赏
  • 举报
回复
public class Http{ } public interface HttpHandle<T> { String getClassName(); } public static void main(String[] args) { HttpHandle handle = new HttpHandle<Http>(){ @Override public String getClassName() { return Http.class.getName(); } }; debug(handle); } static void debug(HttpHandle handle){ // 在这里如何获得类名"Http" ? System.out.println(handle.getClassName()); }

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧