举例来讲getClass( )和getSimpleName( )的区别。
1. 接口
//定义一个接口
package com.test;
public interface Fruit{
}
2. 实现类
//接口Fruit的一个实现类
pack com.test;
public class Apple implements Fruit{
}
3. 基本测试类
package com.test;
import java.util.ArrayList;
import java.util.List;
public class TestName {
public static void main(String[] args) {
//接口实现类
Fruit apple = new Apple();
System.out.println(apple.getClass().getCanonicalName());//com.test.Apple
System.out.println(apple.getClass().getSimpleName());//Apple
System.out.println(apple.getClass().getName());//com.test.Apple
//数组
Apple[] arrApple = new Apple[]{};
//com.test.Apple[]
System.out.println(arrApple.getClass().getCanonicalName());
System.out.println(arrApple.getClass().getSimpleName());//Apple[]
System.out.println(arrApple.getClass().getName());//[Lcom.test.Apple;
//private final 类型
System.out.println(String.class.getCanonicalName());//java.lang.String
System.out.println(String.class.getSimpleName());//String
System.out.println(String.class.getName());//java.lang.String
//基本类型
System.out.println(int.class.getCanonicalName());//返回int
System.out.println(int.class.getSimpleName());//返回int
System.out.println(int.class.getName());//返回int
//集合类型
Apple a1 = new Apple();
Apple a2 = new Apple();
List<Apple> appleList = new ArrayList<Apple>();
appleList.add(a1);
appleList.add(a2);
//java.util.ArrayList
System.out.println(appleList.getClass().getCanonicalName());
System.out.println(appleList.getClass().getSimpleName());//ArrayList
System.out.println(appleList.getClass().getName());//java.util.ArrayList
}
}
4. 在HQL中实例应用
public <T> List<T> getRecords(Class<T> c, Data startData, Data endData){
StringBuilder hql = new StringBuilder("selevt t from ");
hql.append(c.getCanonicalName());
hql.append("t where t.startTime>=:startDataTime and t.startTime<:endTime ");
Query query = sessionFactory.getCurrentSession().createQuery(hql.toString);
query.setParameter("startTime",startData);
query.setParameter("endTimer",endData);
return query.list();
}
5. 总结
注意:Class类是获取类的类模板的实例对象,通过反射的机制获取。根据API中的定义,Class.getSimpleName( )方法是获取源代码中给出的”底层类”的简称。而Class.getName( )是以String的形式,返回Class对象的”实体”名称。
本文详细解析了Java中getClass()方法的使用及其与getSimpleName()和getName()的区别,通过具体的代码示例展示了不同类型的变量(如接口实现类、数组、私有最终类型等)调用这些方法时的不同表现。
154

被折叠的 条评论
为什么被折叠?



