0

我正在尝试在 JSP 页面中打印函数变量的值。函数变量位于 java.class(com.project.bulk) 中。文件名为 bulk.class。我尝试通过在 JSP 文件中编写以下代码来读取变量,但它不起作用。请问有什么帮助吗?

<%@ page import="com.project.bulk.bulk" %>

<%=bulk.cellStoreVector %>

// 函数代码如下

private static void printCellDataToConsole(Vector dataHolder) {

            for (int i = 0; i < dataHolder.size(); i++) {
                    Vector  cellStoreVector  = (Vector) dataHolder.elementAt(i);
                    System.out.println(cellStoreVector);
                    for (int j = 0; j < cellStoreVector.size(); j++) {
                          HSSFCell myCell = (HSSFCell) cellStoreVector.elementAt(j);
                          String stringCellValue = myCell.toString();
                         // System.out.print(stringCellValue + "\t\t");
                    }
                    System.out.println();
            }
    }
4

1 回答 1

2

您不能访问该方法或定义它的块之外的局部变量。局部变量的范围被限制在定义它的块中。

您的以下声明对于声明它的地方是本地的for-loop。即使在当前方法中,它也无法在for-loop. 因为您的循环scope为此变量定义了访问权限:-

Vector  cellStoreVector  = (Vector) dataHolder.elementAt(i);

JSP要在您的外部访问它,请class将该字段声明为您的类中的私有实例变量。并有一个public访问器方法,它将返回该字段的值。然后在您的 JSP 中,您可以调用该方法来获取特定实例的值。

请记住,您需要在instance您的类中访问该方法。您正在通过您的class name. 如果你想这样访问它,你需要一个static变量。

这是一个简单的示例,涵盖了我上面所说的所有内容:-

public class Dog {

    // Private Instance variable
    private int instanceVar; // Defaulted to 0

    // Private Static variable
    // Common for all instances
    private static String name = "rohit";


    // Public accessor
    public int getInstanceVar() {
        return this.instanceVar;
    }

    public void setInstanceVar(int instanceVar) {
        this.instanceVar = instanceVar;
    }

    // Static public accessor for static variable
    public static String getName() {
        return name;
    }

}

class Test {
    public static void main(String[] args) {
        // Access static method through class name
        System.out.println(Dog.getName()); 

        Dog dog = new Dog();

        // Set instance variable through public accessor, on a particular instance
        dog.setInstanceVar(10);

        // Get instance variable value and asssign to local variable x
        // x is local variable in `main`
        int x = dog.getInstanceVar(); 

        showX(); 
    }

    public static void showX() {

        // x not visible here.
        System.out.println(x);  // Will not compile
    }
}
于 2012-10-15T11:54:06.980 回答