要将方法的字符串参数从一个类传递到同一个命名空间中的另一个类,可以通过以下几种方式实现:
public class TargetClass {
private String param;
public TargetClass(String param) {
this.param = param;
}
public void method() {
System.out.println("The parameter is: " + param);
}
}
public class SourceClass {
public void test() {
String param = "Hello";
TargetClass target = new TargetClass(param);
target.method();
}
}
public class TargetClass {
private String param;
public void setParam(String param) {
this.param = param;
}
public void method() {
System.out.println("The parameter is: " + param);
}
}
public class SourceClass {
public void test() {
String param = "Hello";
TargetClass target = new TargetClass();
target.setParam(param);
target.method();
}
}
public class TargetClass {
public static String param;
public void method() {
System.out.println("The parameter is: " + param);
}
}
public class SourceClass {
public void test() {
String param = "Hello";
TargetClass.param = param;
TargetClass target = new TargetClass();
target.method();
}
}
public interface ParamProvider {
String getParam();
}
public class TargetClass implements ParamProvider {
private String param;
public TargetClass(String param) {
this.param = param;
}
public void method() {
System.out.println("The parameter is: " + param);
}
@Override
public String getParam() {
return param;
}
}
public class SourceClass {
public void test() {
String param = "Hello";
TargetClass target = new TargetClass(param);
System.out.println("The parameter is: " + target.getParam());
target.method();
}
}
以上是一些将方法的字符串参数从一个类传递到同一个命名空间中的另一个类的方法。具体实现方式取决于具体需求和场景。
领取专属 10元无门槛券
手把手带您无忧上云