简体   繁体   English

从另一个 class 文件访问方法?

[英]Accesing a method from another class file?

I need to acces a variable (an int) from another class file.我需要从另一个 class 文件中访问一个变量(一个 int)。 How would I do this?我该怎么做? It's a public int, I need to get the int value and put it into a file.这是一个公共 int,我需要获取 int 值并将其放入文件中。

If you have an instance:如果你有一个实例:

AnotherClass another = new AnotherClass();

Then if the field (instance variable) is public:那么如果字段(实例变量)是公共的:

another.someField;

or if you have a getter method或者如果你有一个 getter 方法

another.getSomeField(); 

If none of these is true - add a getter method (this is the preferred way to access instance variables).如果这些都不正确 - 添加一个 getter 方法(这是访问实例变量的首选方法)。

If you can't change the class - as a last resort you can use reflection .如果您无法更改 class - 作为最后的手段,您可以使用反射

Example:例子:


    MyClass myclass = new MyClass();
    System.out.print(myclass.myint)

Best practice code states that if the variable is not a Static Final, then you should create getters & setters inside the class:最佳实践代码指出,如果变量不是 Static Final,那么您应该在 class 中创建 getter 和 setter:

public class Main{
   int variableName;

   public int getVariableName(){
       return this.variableName;
   }
   public setVariableName(int variableName){
       this.variableName = variableName;
   }
}

If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method:如果你想从另一个 class 文件访问它,那么你必须实例化一个 Object 然后使用公共方法访问它:

Main m = new Main();
int a = m.getVariableName();

Hope it helps.希望能帮助到你。

If you have an instance of that other class, you access it as {instance}.varable.如果您有另一个 class 的实例,您可以将其作为 {instance}.varable 访问。

That varaiable need to either be public, or it needs to be in the same package and not private, or it must be a protected variable in a superclass.该变量需要是公共的,或者它需要在同一个 package 中而不是私有的,或者它必须是超类中的受保护变量。

If the variable is static, then you don't need an instance of that class, you would access it like {ClassName}.variable.如果变量是 static,那么您不需要该 class 的实例,您可以像 {ClassName}.variable 一样访问它。

Far and away the best thing to do here would be to make the int you need to access a Property of the other class and then access it with a 'getter' method.在这里要做的最好的事情就是让 int 访问另一个 class 的属性,然后使用“getter”方法访问它。

Basically, in the other class, do this:基本上,在另一个 class 中,这样做:

public int Number    
{
  get
  {
    return number;
  }
  set
  {
    number = value;
  }
}
private int number;

Doing this allows you to easily set that in to something else if you need to or to get it's current value.这样做可以让您在需要时轻松地将其设置为其他内容或获取它的当前值。 To do this, create an instance of the "AnotherClass" as Bozho already explained.为此,请创建一个 Bozho 已经解释过的“AnotherClass”实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM