interface STD{
public Name getName();
}
class Student implements STD{
Name getName(){ }
private class Name{
}
}
在上面的代码中,界面无法看到私有类名称,有没有办法让它看到它,而它是一个私有内部类来定义它的数据类型?
答案 0 :(得分:1)
protected class Name
使用受保护的变量,以便界面可以看到它,但不能看到任何其他不直接相关的类
答案 1 :(得分:0)
你不想这样做。 private
意味着......私密。
您可能想要做的是在Name
之外声明Student
(这是有道理的,Name
实体不应仅限于学生):
public class Student implements STD {
public Name getName() {
// ...
}
}
interface STD {
public Name getName();
}
class Name { }
请注意,您可以将Name
放在单独的文件中,这取决于您和您的需要放置位置。
答案 2 :(得分:0)
这对你有用:
package test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
interface STD{
public Object getName();
}
class Student implements STD {
@Override
public Name getName() {
return null;
}
private class Name {
private int myField = 5;
}
public static void main(String[] args) {
try {
Student outer = new Student();
// List all available constructors.
// We must use the method getDeclaredConstructors() instead
// of getConstructors() to get also private constructors.
for (Constructor<?> ctor : Student.Name.class
.getDeclaredConstructors()) {
System.out.println(ctor);
}
// Try to get the constructor with the expected signature.
Constructor<Name> ctor = Student.Name.class.getDeclaredConstructor(Student.class);
// This forces the security manager to allow a call
ctor.setAccessible(true);
// the call
Student.Name inner = ctor.newInstance(outer);
System.out.println(inner);
Field privateField = Class.forName("test.Student$Name").getDeclaredField("myField");
//turning off access check with below method call
privateField.setAccessible(true);
System.out.println(privateField.get(inner)); // prints "5"
privateField.set(inner, 20);
System.out.println(privateField.get(inner)); //prints "20"
} catch (Exception e) {
System.out.println("ex : " + e);
}
}
}