读书人

关于使用反射机制得到泛型的字段名的有

发布时间: 2012-08-10 12:19:33 作者: rapoo

关于使用反射机制得到泛型的字段名的问题
1、实体类

import java.lang.reflect.Field;import org.junit.Test;public class TestReflect {@Testpublic void test() {//可以得到字段名LSLSEntry entry = new LSLSEntry();printValue(entry);}@Testpublic void test1() {//得不到字段名,为什么???printValue(LSLSEntry.class);}@Testpublic void test2() {//得不到字段名,为什么??PrintInfo2<LSLSEntry> info = new PrintInfo2<LSLSEntry>(LSLSEntry.class);info.printValue();}@Testpublic void test3() {//可以得到字段名LSLSEntry entry = new LSLSEntry();PrintInfo<LSLSEntry> info = new PrintInfo<LSLSEntry>(entry);info.printValue();}@Testpublic void test4() {//可以得到字段名Field[] fields = LSLSEntry.class.getFields();for (Field f : fields) {System.out.println(f.getName());}}private <T> void printValue(T entry) {Field[] fields = entry.getClass().getFields();for (Field f : fields) {System.out.println(f.getName());}}private class PrintInfo<T> {T entry;public PrintInfo(T entry) {this.entry = entry;}private void printValue() {Field[] fields = entry.getClass().getFields();for (Field f : fields) {System.out.println(f.getName());}}}private class PrintInfo2<T> {Class<?> entry;public PrintInfo2(Class<?> entry) {this.entry = entry;}private void printValue() {Field[] fields = entry.getClass().getFields();for (Field f : fields) {System.out.println(f.getName());}}}}
在做项目的时候遇到这个问题,在反射泛型的字段时,只要将要反射的类实例化之后,反射其所对应的引用才能得到其字段,而直接反射类得不到。网上查询了好长时间没有找到答案,贴出来,求答案……

读书人网 >编程

热点推荐