首页 > 解决方案 > Java 语言:“this”关键字用法(在 Talend tJavaRow 中使用)

问题描述

在 Talend 中,我正在编写一些小代码,在 MetaData“代码”区域中编写一个类,可以编写 java 类,然后在组件 tJavaRow 中,可以调用该类的方法。

因此,当我创建类并在 tJavaRow 中写入类的名称然后是一个点时,我遇到了这种情况,出现的上下文对话框没有显示方法,而是显示了“this”关键字以及其他内容。我决定使用“this”,然后放一个点,然后出现上下文对话框来显示类中的方法。

我的问题是关键字“this”是否能够将一个类隐式实例化为一个对象,这就是为什么我能够看到该类的方法的原因?

我只是决定将我的一种方法更改为静态方法并以这种方式使用它。

那么如果关键字'this'可以将类实例化为对象而不使用'new'关键字将java类实例化为对象是正确的?

我对此进行了一些研究,我发现了关键字“this”可以做的事情的列表。

这个关键字的使用

It can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
**It can be used to invoke current class method (implicitly)**
It can be passed as an argument in the method call.
It can be passed as argument in the constructor call.
It can also be used to return the current class instance.

所以举个代码例子来说明:假设我们有一个名为mySphere的类,并且我们有方法mySurfaceArea和myVolume,我们可以这样调用方法吗:

mySphere.this.mySurfaceArea();

mySphere.this.myVolume();


输入表示赞赏!

我刚刚在此创建了自己的代码并运行它,但出现错误:

public class MyClass {
    public static void main(String args[]) {
        int x=10;
        int y=25;
        int z=x+y;
        int w;

        System.out.println("Sum of x+y = " + z);
        w = MyClass.this.myAreaCalc(x);
        System.out.println("Area Calc is = " + w);
    }
    
    public int myAreaCalc(int A){
        return A*A;
    }
    
}


Error:
/MyClass.java:9: error: non-static variable this cannot be referenced from a static context
        w = MyClass.this.myAreaCalc(x);
                   ^
1 error




标签: javatalend

解决方案


<ClassName>.thisthis您在类上下文中时对象的快捷方式。

由于您处于静态上下文中,public static void main因此无法从此处访问非静态实例。

您的代码需要实例化类的对象并通过实例对象使用其非静态方法。

public static void main(String args[]) {
    int x=10;
    int y=25;
    int z=x+y;
    int w;

    System.out.println("Sum of x+y = " + z);
    w = new MyClass().myAreaCalc(x);
    System.out.println("Area Calc is = " + w);
}

在这种情况下,of 的用法<ClassName>.this是对外部类的引用:

public class A {
    class B {
        void x () { A outer = A.this; }
    }
    B create() { return new B(); }
}

在这种情况下,只有在 A 的实例上下文中,您才能在示例中创建 B 的对象,使用B b = new A().create()或 回答有关上下文的问题

A ao = new A();
B b = ao.new B();

如果您在两个实例上下文中具有相同的名称,那么匿名和子类上的 ClassName.this 的用法也用于变量区分。


推荐阅读