【发布时间】: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