简体   繁体   English

如何在另一个Java类中访问对象的公共方法

[英]How to access the object present i na public method of a class in another Java class

File 1: I have a public method which contain the declaration of a object. 文件1:我有一个包含对象声明的公共方法。

File 2: I want to import this class and want to acess the object. 文件2:我想导入这个类,并希望访问该对象。

the object in file 1 is 文件1中的对象是

public stamp1
{
PdfReader reader = new PdfReader(sourceTemplatePDFUrlStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);
}

so how to acess it in file 2: 所以如何在文件2中访问它:

import file.*;

What to do here? 该怎么办?

You should rethink your program if you have to do something as terrible as this. 如果你必须做一些像这样糟糕的事情,你应该重新考虑你的计划。

This is what class variables are for. 这是类变量的用途。 Declare reader and stamper as private variables then use getters to get it form outside your class: readerstamper声明为私有变量,然后使用getter在类外部获取它:

public class MyClass {
    private PdfReader reader;
    private PdfStamper stamper;

    public void stamp1() {
        // ...
        reader = new PdfReader(sourceTemplatePDFUrlStream);
        stamper = new PdfStamper(reader, outputStream);
    }

    public PdfReader getReader() {
        return reader;
    }

    public PdfStamper getStamper() {
        return stamper;
    }
}

You can't. 你不能。 An object in a public method is a local variable, only available in that method while the method is executed. 公共方法中的对象是局部变量,仅在执行方法时在该方法中可用。

A method can return such objects, then you can get it. 一个方法可以返回这样的对象,然后你就可以得到它。 Or the object is saved as attribute, then there might be a getter to get it, or it could be visible. 或者将对象保存为属性,然后可能有一个getter来获取它,或者它可以是可见的。

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

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