场景:测试 私有内部类
目标源码:
public class Demo{
private static final class ByteArrayHashIndexEntry {
private int hashCode;
private byte[] key;
private byte[] value;
private ByteArrayHashIndexEntry nextEntry;
/**
* @param hashCode
* @param key
* @param value
* @param nextEntry
*/
public ByteArrayHashIndexEntry( int hashCode, byte[] key, byte[] value, ByteArrayHashIndexEntry nextEntry ) {
this.hashCode = hashCode;
this.key = key;
this.value = value;
this.nextEntry = nextEntry;
}
public boolean equalsKey( byte[] cmpKey ) {
return equalsByteArray( key, cmpKey );
}
@Override
public boolean equals( Object obj ) {
ByteArrayHashIndexEntry e = (ByteArrayHashIndexEntry) obj;
return equalsValue( e.value );
}
public boolean equalsValue( byte[] cmpValue ) {
return equalsByteArray( value, cmpValue );
}
public static final boolean equalsByteArray( byte[] value, byte[] cmpValue ) {
if ( value.length != cmpValue.length ) {
return false;
}
for ( int i = value.length - 1; i >= 0; i-- ) {
if ( value[i] != cmpValue[i] ) {
return false;
}
}
return true;
}
}
}
测试代码:
public void reflectByteArrayHashIndexEntry() throws Exception{
Object object = null;
Class<ByteArrayHashIndex> clazz = ByteArrayHashIndex.class;
//获取外部类内的所有内部类
Class<?>[] declaredClasses = clazz.getDeclaredClasses();
for (Class c : declaredClasses){
//获取修饰符的整数编码
int mod = c.getModifiers();
//返回整数编码对应的修饰符的字符串对象
String modifier = Modifier.toString(mod);
//找到被private修饰的内部类
if (modifier.contains("private")) {
int hashCode = 1;
byte[] key = {10,11};
byte[] value = {23,24};
byte[] value1 = {23,24,25,26};
//获取内部类的构造方法
Constructor[] constructors = c.getConstructors();
//设置访问权限
AccessibleObject.setAccessible(constructors, true);
//遍历
for (Constructor constructor1 : constructors){
//创建内部类对象
object = constructor1.newInstance(hashCode, key, value, null);
if (null != object){
break;
}
}
Field hashCode1 = c.getDeclaredField("hashCode");
hashCode1.setAccessible(true);
hashCode1.set(object,0);
//获取内部类的方法
Method equals = c.getMethod("equals", Object.class);
// 执行
assertTrue((Boolean) equals.invoke(object, object));
break;
}
}
}