简体   繁体   中英

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.

File 2: I want to import this class and want to acess the object.

the object in file 1 is

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

so how to acess it in file 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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