1、public native Class<?> getComponentType();
该函数在Class<T>类中,如果该Class类对象属于数组类型,那么就返回对应的Class对象,如果不是数组类型那么就返回null,示例代码:
BitSet []bitset = new BitSet[1];//非基本数据类型的数组类型
System.out.println(bitset.getClass().getComponentType());
long []l = {1};//基本数据类型(byte short int long float double char boolean)的数组类型
System.out.println(l.getClass().getComponentType());
Integer a = new Integer(10);//非数组类型
System.out.println(a.getClass().getComponentType());
运行结果如下:
class java.util.BitSet
long
null
2、public native boolean isPrimitive();
该函数在Class<T>类中,判断该类是否属于基本数据类型,示例代码如下:
Class stringClass=String.class;
System.out.println("String is primitive type:"+stringClass.isPrimitive());
Class booleanClass=Boolean.class;
System.out.println("Boolean is primitive type:"+booleanClass.isPrimitive());
Class booleanType=boolean.class;
System.out.println("boolean is primitive type:"+booleanType.isPrimitive());
Class byteType=byte.class;
System.out.println("byte is primitive type:"+byteType.isPrimitive());
Class charType=char.class;
System.out.println("char is primitive type:"+charType.isPrimitive());
Class shortType=short.class;
System.out.println("short is primitive type:"+shortType.isPrimitive());
Class intType=int.class;
System.out.println("int is primitive type:"+intType.isPrimitive());
Class longType=long.class;
System.out.println("long is primitive type:"+longType.isPrimitive());
Class floatType=float.class;
System.out.println("float is primitive type:"+floatType.isPrimitive());
Class doubleType=double.class;
System.out.println("double is primitive type:"+doubleType.isPrimitive());
运行结果如下:
String is primitive type:false
Boolean is primitive type:false
boolean is primitive type:true
byte is primitive type:true
char is primitive type:true
short is primitive type:true
int is primitive type:true
long is primitive type:true
float is primitive type:true
double is primitive type:true
3、String.intern()函数,该函数属于String类,示例代码如下
String a = "a";
String b = "b";
String c = "ab";
String d = new String("ab");
String e = a + b;
System.out.println(c.intern() == d);
System.out.println(c.intern() == e);
System.out.println(c.intern() == d.intern());
System.out.println(c.intern() == e.intern());
System.out.println(d.intern() == e);
System.out.println(d.intern() == e.intern());
运行结果:
false
false
true
true
false
true
主要的原理如下:
String类对象调用intern函数会先到字符串池中去找相同值(通过equals函数来判断)的对象,如果找到了那么就返回该对象,如果没有找到那么就在字符串池中创建该对象并返回该对象,我们来分析上面的代码:
第一行,c.intern() == d
c.intern函数返回的是字符串池中的对象,而d是通过new String创建的,所以该对象不会进入到字符串池中,因此两个对象不一样
第二行,c.intern() == e
由于e是通过a+b产生的,而a和b都是变量,所以这种情况下产生的e对象不会进入到字符串池中
后面几行都类似,参考资料