在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
答案 0 :(得分:1)
<ClassName>.this
是this
对象的快捷方式,而您处于类上下文中。
由于您位于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);
}
在这种情况下,<ClassName>.this
的使用是对外部类的引用:
public class A {
class B {
void x () { A outer = A.this; }
}
B create() { return new B(); }
}
在这种情况下,只有在A的实例上下文中,您才能在示例中使用B b = new A().create()
来创建对象B或回答有关上下文的问题
A ao = new A();
B b = ao.new B();
如果在两个实例上下文中名称相同,则匿名类和子类也使用ClassName.this进行变量区分。
答案 1 :(得分:0)
我想我明白你在这里追求什么。在“当前类”上使用this
仍然意味着您需要调用new
。在类中,您可以使用this
来引用实例成员。 (“实例”比说“当前类”更好,因为您确实需要一个实例,不能仅使用类类型。)
类似这样:
public class MyClass {
private final int area;
public MyClass( int a ) {
area = a;
}
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);
MyClass mc = new MyClass( x );
w = mc.myAreaCalc();
System.out.println("Area Calc is = " + w);
}
public int myAreaCalc(){
return this.area * this.area;
}
}
答案 2 :(得分:0)
我相信您感到困惑的那行是指我在下面的代码中放入的这个示例:
public class MyClass {
public MyClass() { //Note this is now a Constructor, not a public static method
int x=10;
int y=25;
int z=x+y;
int w;
System.out.println("Sum of x+y = " + z);
w = this.myAreaCalc(x); //These two lines are the same
w = myAreaCalc(x); //These two lines are the same
System.out.println("Area Calc is = " + w);
}
public int myAreaCalc(int A){
return A*A;
}
}
在非静态上下文中,您可以使用this.method()
调用方法,但是this
被隐式调用,并且可以从同一method()
用作Class
。
注意:您不能通过静态方法使用this
来自 的方法,否则会得到一个错误,并使用它来调用非静态方法中的静态方法会给您警告。