interface STD{
public Name getName();
}
class Student implements STD{
Name getName(){ }
private class Name{
}
}
在接口上面的代碼無法看到私有類名稱,是否有辦法讓它看到它,而它是一個私有內部類從定義的數據類型它?定義數據類型從內部私有類
interface STD{
public Name getName();
}
class Student implements STD{
Name getName(){ }
private class Name{
}
}
在接口上面的代碼無法看到私有類名稱,是否有辦法讓它看到它,而它是一個私有內部類從定義的數據類型它?定義數據類型從內部私有類
你不想這樣做。 private
是爲了..私人。
你可能想要做什麼是聲明Name
外Student
(很有意義,Name
實體不應該綁只是學生):
public class Student implements STD {
public Name getName() {
// ...
}
}
interface STD {
public Name getName();
}
class Name { }
注意,您可以在一個單獨的文件中有Name
,這取決於你和你的需求在哪裏放置它。
這會爲你工作:
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);
}
}
}
protected class Name
使用受保護的變量,這樣的界面可以看到它,但並不是說沒有直接關係的任何其他類
你爲什麼要做這個?通過非私人方法提供私人課程通常不是一個好主意...... – fabian
這是一個已經呈現給我的問題,我試圖解決它^^ – Trickster