在复习Java准备考试,由于书使用的是jdk6版本有一些和我使用的jdk13不一致的地方
我又比较喜欢“抬杠”,今天我就来”杠一杠“
都是些很简单的操作
另外一提这本书是Java大学实用教程(第四版) 耿祥义 张跃平
public class AntiBook {
@AllArgsConstructor
class ExampleClass {
private String name;
private String password;
private void say(){
System.out.println("I am private");
}
}
interface ExampleInterface{
default void say(){
System.out.println("i can say");
}
static void sayLoudly(){
System.out.println("i can say loudly");
}
void sayLightly();
}
//private无法被直接访问,但不代表着无法访问
@Test
@SneakyThrows
public void readPrivateField(){
ExampleClass exampleClass = new ExampleClass("name", "password");
for (Field field : exampleClass.getClass().getDeclaredFields()) {
field.setAccessible(true);
System.out.println(field.getName()+"字段的类型为"+field.getType()+",值为"+field.get(exampleClass));
}
}
@Test
@SneakyThrows
public void invokePrivateMethod(){
ExampleClass exampleClass = new ExampleClass("name", "password");
Method method = exampleClass.getClass().getDeclaredMethod("say");
method.setAccessible(true);
method.invoke(exampleClass);
}
//匿名类无法调用自己扩展的方法吗?
@Test
public void callAnonymousClassOwnMethod(){
//这个是个java自带的空接口,很显然这两个方法只能调用一个,且只能调用一次就被向上转型了
new Serializable(){
public Serializable sayFirst(){
System.out.println("I am anonymous");
return this;
}
public Object saySecond(){
System.out.println("I also am anonymous");
return this;
}
}.sayFirst();
}
@Test
@SneakyThrows
public void callAnonymousClassOwnMethodByReflection(){
//这个是个java自带的空接口
Serializable s = new Serializable() {
{}
public Serializable sayFirst() {
System.out.println("I am anonymous");
return this;
}
public Object saySecond() {
System.out.println("I also am anonymous");
return this;
}
};
for (Method method : s.getClass().getDeclaredMethods()) {
method.invoke(s);
}
Class<?> aClass = Class.forName("Example.AntiBook$2");
Object o = aClass.getDeclaredConstructor(AntiBook.class).newInstance(new AntiBook());
for (Method method : o.getClass().getDeclaredMethods()) {
method.invoke(o);
}
}
//接口方法无默认实现吗???
@Test
public void interfaceContainDefaultMethod(){
//调用静态接口方法,无需实例化
ExampleInterface.sayLoudly();
ExampleInterface e = new ExampleInterface() {
@Override
public void sayLightly() {
System.out.println("i say silently");
}
};
e.sayLightly();
//default提供默认方法
e.say();
}
}