【问题标题】:Accessing a private variable from another class从另一个类访问私有变量
【发布时间】:2013-12-19 02:22:04
【问题描述】:

注意:我看过其他帖子,但我还是很迷茫。

这是我在一个类中的私有变量的代码:

private int readFile( String fileName)  
{
 try
 {
            File f = new File( fileName );
            Scanner input = new Scanner( f );
            while( input.hasNextLine( ) )
            {
                    String s = input.nextLine( );
                    String[ ] sArr = s.split( " " );
                    String animal = sArr[ 0 ];
                    double cost = Double.parseDouble(sArr [ 1 ] );
                    boolean penNeeded = Boolean.parseBoolean( sArr[ 2 ] );
                    boolean available = Boolean.parseBoolean( sArr[ 3 ] );
                    Pet p = new Pet( animal, cost, penNeeded, available );
                    if (count < animalList.length )
                    {
                       animalList[count] = p;
                       count++;
                    }
            }
            input.close( );
        }
        catch( Exception e )
        {
          System.out.println("Error reading the file:");
          System.out.println( e );
          e.printStackTrace(  );
        }

        return count;
  }

我需要在位于另一个类的这段代码中访问它:

 static public void processTransaction( String fileName, PettingZoo pz )
 {
    try
    {
       // variable should be accessed here                  
    }
    catch( Exception e )
    {
        System.out.println("Error reading the file:");
        System.out.println( e );
        e.printStackTrace(  );
    }
}

我该怎么做?我认为我需要使用某种修饰符,但我不知道如何使用它或如何实现它。

【问题讨论】:

  • 你能在你的方法之外声明这个变量,然后为那个变量创建一个getter/setter方法吗?
  • 我没有得到你的问题。我猜你想访问private int readFile(String fileName) 方法?不正确?
  • 什么“私有变量”?您展示了一个声明为 private ... 的方法,这意味着您无法从另一个类访问它。
  • 你必须使用gettter和setter
  • @Jayamohan 是的,这就是我想要访问的方法。

标签: java variables reflection private


【解决方案1】:

您不能直接访问另一个类的私有变量。这就是将其声明为私有的全部意义所在。您需要做的是在A 类中使用settergetter 方法,然后从B 类中调用get 方法。

【讨论】:

    【解决方案2】:

    如果要访问私有变量,可以使用 getter 和 setter 方法。

    例子:

    private int variable = 5; //<--- your private variable of class A
    
    // a public method (into the same class A)
    // that allows the sharing of your private variable
    public int getVariable() {
        return variable;
    }
    

    现在您可以从其他类 (B) 调用方法 getVariable() 并获取(类 A)的私有变量的值。

    【讨论】:

      【解决方案3】:

      根据your comment,您可以通过更改方法的修改来访问private int readFile(String fileName) 方法。将方法的修饰符更改为publicprotected。另外由于访问方法是static,所以需要将方法改成static

      所以改成

      public static int readFile( String fileName)  
      {
      
      }
      

      processTransaction 方法中调用它,

      ClassName.readFile("file_name.extn");
      

      【讨论】:

        猜你喜欢
        • 2017-03-08
        • 1970-01-01
        • 2020-09-02
        • 1970-01-01
        • 1970-01-01
        • 2014-09-05
        • 2020-12-20
        • 1970-01-01
        相关资源
        最近更新 更多