익명 클래스에 매개 변수를 전달하는 방법은 무엇입니까?
익명 클래스에 매개 변수를 전달하거나 외부 매개 변수에 액세스 할 수 있습니까? 예를 들면 다음과 같습니다.
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// How would one access myVariable here?
}
});
리스너가 실제 이름 지정된 클래스로 리스너를 작성하지 않고 myVariable에 액세스하거나 myVariable에 전달할 수있는 방법이 있습니까?
익명 클래스는 생성자를 가질 수 없기 때문에 기술적으로는 아닙니다.
그러나 클래스는 범위를 포함하여 변수를 참조 할 수 있습니다. 익명 클래스의 경우 포함 클래스의 인스턴스 변수 또는 final로 표시된 로컬 변수 일 수 있습니다.
편집 : Peter가 지적했듯이 매개 변수를 익명 클래스의 수퍼 클래스 생성자에게 전달할 수도 있습니다.
예, 'this'를 반환하는 초기화 메소드를 추가하고 즉시 해당 메소드를 호출하면됩니다.
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
private int anonVar;
public void actionPerformed(ActionEvent e) {
// How would one access myVariable here?
// It's now here:
System.out.println("Initialized with value: " + anonVar);
}
private ActionListener init(int var){
anonVar = var;
return this;
}
}.init(myVariable) );
'최종'선언이 필요하지 않습니다.
예. 내부 클래스에서 볼 수있는 변수를 캡처 할 수 있습니다. 유일한 한계는 그것이 최종적 이어야한다는 것입니다
이처럼 :
final int myVariable = 1;
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Now you can access it alright.
}
});
이것은 마술을 할 것입니다
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
int myVariable;
public void actionPerformed(ActionEvent e) {
// myVariable ...
}
public ActionListener setParams(int myVariable) {
this.myVariable = myVariable;
return this;
}
}.setParams(myVariable));
http://www.coderanch.com/t/567294/java/java/declare-constructor-anonymous-class에 표시된 것처럼 인스턴스 이니셜 라이저를 추가 할 수 있습니다. 이름이없고 생성자와 마찬가지로 먼저 실행되는 블록입니다.
왜 Java 인스턴스 초기화 프로그램인가? 에서 논의 된 것처럼 보입니다 . 인스턴스 이니셜 라이저는 생성자 와 어떻게 다릅니 까? 생성자와의 차이점에 대해 설명합니다.
내 솔루션은 구현 된 익명 클래스를 반환하는 메서드를 사용하는 것입니다. 정규 인수는 메소드에 전달 될 수 있으며 익명 클래스 내에서 사용 가능합니다.
For example: (from some GWT code to handle a Text box change):
/* Regular method. Returns the required interface/abstract/class
Arguments are defined as final */
private ChangeHandler newNameChangeHandler(final String axisId, final Logger logger) {
// Return a new anonymous class
return new ChangeHandler() {
public void onChange(ChangeEvent event) {
// Access method scope variables
logger.fine(axisId)
}
};
}
For this example, the new anonymous class-method would be referenced with:
textBox.addChangeHandler(newNameChangeHandler(myAxisName, myLogger))
OR, using the OP's requirements:
private ActionListener newActionListener(final int aVariable) {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Your variable is: " + aVariable);
}
};
}
...
int myVariable = 1;
newActionListener(myVariable);
Other people have already answered that anonymous classes can access only final variables. But they leave the question open how to keep the original variable non-final. Adam Mlodzinski gave a solution but is is pretty bloated. There is a much simpler solution for the problem:
If you do not want myVariable
to be final you have to wrap it in a new scope where it does not matter, if it is final.
int myVariable = 1;
{
final int anonVar = myVariable;
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// How would one access myVariable here?
// Use anonVar instead of myVariable
}
});
}
Adam Mlodzinski does not do anything else in his answer but with much more code.
You can use plain lambdas ("lambda expressions can capture variables")
int myVariable = 1;
ActionListener al = ae->System.out.println(myVariable);
myButton.addActionListener( al );
or even a Function
Function<Integer,ActionListener> printInt =
intvar -> ae -> System.out.println(intvar);
int myVariable = 1;
myButton.addActionListener( printInt.apply(myVariable) );
Using Function is a great way to refactor Decorators and Adapters, see here
I've just started learning about lambdas, so if you spot a mistake, feel free to write a comment.
A simple way for put some value into a external variable(doesn't belong for anonymus class) is how folow!
In the same way if you want get the value of a external variable you can create a method that return what you want!
public class Example{
private TypeParameter parameter;
private void setMethod(TypeParameter parameter){
this.parameter = parameter;
}
//...
//into the anonymus class
new AnonymusClass(){
final TypeParameter parameterFinal = something;
//you can call setMethod(TypeParameter parameter) here and pass the
//parameterFinal
setMethod(parameterFinal);
//now the variable out the class anonymus has the value of
//of parameterFinal
});
}
I thought anonymous classes were basically like lambdas but with worse syntax... this turns out to be true but the syntax is even worse and causes (what should be) local variables to bleed out into the containing class.
You can access none final variables by making them into fields of the parent class.
Eg
Interface:
public interface TextProcessor
{
public String Process(String text);
}
class:
private String _key;
public String toJson()
{
TextProcessor textProcessor = new TextProcessor() {
@Override
public String Process(String text)
{
return _key + ":" + text;
}
};
JSONTypeProcessor typeProcessor = new JSONTypeProcessor(textProcessor);
foreach(String key : keys)
{
_key = key;
typeProcessor.doStuffThatUsesLambda();
}
I dont know if they've sorted this out in java 8 (I'm stuck in EE world and not got 8 yet) but in C# it would look like this:
public string ToJson()
{
string key = null;
var typeProcessor = new JSONTypeProcessor(text => key + ":" + text);
foreach (var theKey in keys)
{
key = theKey;
typeProcessor.doStuffThatUsesLambda();
}
}
You dont need a seperate interface in c# either... I miss it! I find myself making worse designs in java and repeating myself more because the amount of code + complexity you have to add in java to reuse something is worse than just copy and pasting a lot of the time.
참고URL : https://stackoverflow.com/questions/5107158/how-to-pass-parameters-to-anonymous-class
'IT story' 카테고리의 다른 글
Google과 같은 작업 표시 줄 알림 수 아이콘 (배지) (0) | 2020.06.18 |
---|---|
키는 응용 프로그램 특정 자원 ID 여야합니다. (0) | 2020.06.18 |
라디오 그룹에서 선택한 라디오를 값으로 설정 (0) | 2020.06.18 |
cygwin에 cURL을 어떻게 설치합니까? (0) | 2020.06.18 |
Android에서 애플리케이션 힙 크기 감지 (0) | 2020.06.18 |