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

class Student implements STD{ 
    Name getName(){ } 

    private class Name{ 

    } 
} 

からのデータ型を定義しますそれ?それからデータ型を定義するために、民間の内部クラスですが、それはそれを見るようにする方法があり、プライベートなクラス名を見ることができないインターフェイス上のコードでは、内部プライベートクラス

+0

に関連していない他のクラスのインターフェイスは、それを見ることができるように保護された変数を使用しますが、ではありませんこれを行う?非公開の方法でプライベートクラスを利用できるようにすることは、一般的には良い考えではありません。 – fabian

+0

私に提示された問題です。それを解決しようとしています^^ – Trickster

答えて

0

あなたはそうしたくありません。 privateはプライベートであることを意図しています。

あなたはおそらくやりたいことStudentNameを宣言している(それが意味をなす、Nameエンティティが唯一の学生に縛られるべきではありません):あなたは別のファイルにNameを持つことができ

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

interface STD { 
    public Name getName(); 
} 

class 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 

直接