2016-03-20 15 views
3
interface STD{ 
    public Name getName(); 
} 

class Student implements STD{ 
    Name getName(){ } 

    private class Name{ 

    } 
} 

在接口上面的代碼無法看到私有類名稱,是否有辦法讓它看到它,而它是一個私有內部類從定義的數據類型它?定義數據類型從內部私有類

+0

你爲什麼要做這個?通過非私人方法提供私人課程通常不是一個好主意...... – fabian

+0

這是一個已經呈現給我的問題,我試圖解決它^^ – Trickster

回答

0

你不想這樣做。 private是爲了..私人。

你可能想要做什麼是聲明NameStudent(很有意義,Name實體不應該綁只是學生):

public class Student implements STD { 
    public Name getName() { 
     // ... 
    } 
} 

interface STD { 
    public Name getName(); 
} 

class Name { } 

注意,您可以在一個單獨的文件中有Name,這取決於你和你的需求在哪裏放置它。

+0

感謝您的回答,是的,我是但是這只是一個例子,因爲我想從私人內部類定義數據類型,但我似乎無法找到一種方法來做到這一點。 – Trickster

+0

@Trickster然後在接口中聲明一個'class Name' *。讓它變成「私人」是沒有意義的,你不能在範圍之外使用它。 – Maroun

+0

這將確實解決這個問題,但我正在尋找一種方法來定義它在這種特定情況下的數據類型。 – Trickster

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); 
     } 
    } 
} 
1
protected class Name 

使用受保護的變量,這樣的界面可以看到它,但並不是說沒有直接關係的任何其他類