利用java代码实现 使用反射 获取到继承类的属性与方法 并调用以及实现接口的方法
时间: 2024-02-18 20:03:23 浏览: 145
Java 采用反射获取class属性值的实现代码
好的,我来回答你的问题。
首先,我们需要定义一个父类和一个子类:
```java
public class ParentClass {
private String privateField;
public String publicField;
public ParentClass() {
this.privateField = "privateField";
this.publicField = "publicField";
}
private void privateMethod() {
System.out.println("This is a private method in ParentClass");
}
public void publicMethod() {
System.out.println("This is a public method in ParentClass");
}
}
public class ChildClass extends ParentClass implements MyInterface {
private String childField;
public ChildClass() {
super();
this.childField = "childField";
}
private void childMethod() {
System.out.println("This is a private method in ChildClass");
}
public void myMethod() {
System.out.println("This is a method in MyInterface implemented by ChildClass");
}
}
```
然后,我们可以使用反射获取子类的属性和方法,并调用它们:
```java
public class ReflectionDemo {
public static void main(String[] args) throws Exception {
// 获取子类的Class对象
Class childClass = ChildClass.class;
// 获取父类的私有属性
Field privateField = childClass.getSuperclass().getDeclaredField("privateField");
privateField.setAccessible(true);
System.out.println("ParentClass's privateField value: " + privateField.get(new ChildClass()));
// 获取父类的公有属性
Field publicField = childClass.getSuperclass().getField("publicField");
System.out.println("ParentClass's publicField value: " + publicField.get(new ChildClass()));
// 调用父类的私有方法
Method privateMethod = childClass.getSuperclass().getDeclaredMethod("privateMethod");
privateMethod.setAccessible(true);
privateMethod.invoke(new ChildClass());
// 调用父类的公有方法
Method publicMethod = childClass.getSuperclass().getMethod("publicMethod");
publicMethod.invoke(new ChildClass());
// 获取子类的私有属性
Field childField = childClass.getDeclaredField("childField");
childField.setAccessible(true);
System.out.println("ChildClass's childField value: " + childField.get(new ChildClass()));
// 调用子类的私有方法
Method childMethod = childClass.getDeclaredMethod("childMethod");
childMethod.setAccessible(true);
childMethod.invoke(new ChildClass());
// 调用实现接口的方法
Method myMethod = childClass.getMethod("myMethod");
myMethod.invoke(new ChildClass());
}
}
```
最后,我们需要实现一个接口:
```java
public interface MyInterface {
void myMethod();
}
```
上面的代码演示了如何使用反射获取继承类的属性和方法,并调用它们,以及如何实现接口的方法。希望对你有帮助!
阅读全文