简体   繁体   English

使用构造函数作为方法参数

[英]use a constructor as a method parameter

I'm writing a class that will build a SQL table create statement. 我正在写一个将构建SQL表create语句的类。 what I'd like to do is call a method something like createTable(String tableName ColAndTypes... ct ) . 我想做的是调用诸如createTable(String tableName ColAndTypes... ct ) When I write the method I don't get any compile errors. 当我编写该方法时,没有任何编译错误。 I'm having trouble passing the values into the method when I call it though and I think it's because my syntax is wrong and I'm not sure how to fix it. 我在调用它时很难将值传递到方法中,我认为这是因为我的语法错误并且不确定如何解决。 I was wondering if you could look at the example I have provided and let me know what I need to do to fix it. 我想知道您是否可以看一下我提供的示例,并让我知道修复该问题所需要做的事情。 Thanks so much for your help! 非常感谢你的帮助!

import java.util.*;
public class foo
{
public class bar{
    public String sBar1, sBar2;
    public bar(){
        sBar1 = "null";
        sBar2 = "null";
    }
    public bar(String sBar1, String sBar2){
    this.sBar1 = sBar1;
    this.sBar2 = sBar2;
    }
}

String sFoo;
List<bar> bi;

public foo(){
    sFoo = "null";
    bi = new bar();
}
public foo(Strinf sFoo, bar bi){
    this.sFoo = sFoo;
    this.bi = bi;
}

public void runFooBar(String sFoo, bar... barArgs)
{
    this.sFoo = sFoo;
    for(bar x:barArgs){System.out.Println(bi.get(x).sBar1   + ":" + bi.get(x).sBar2);}
}

public static void main(String[] args)  
{
    foo fi = new foo();
    fi.runFooBar("foo 1", ("1 sBar1","1 sBar2"),("2 sBar1 ","2 sBar2"))

}//end main

}//end class

I'm not entirely sure what you're trying to do, but this fixes your syntax errors. 我不确定您要做什么,但这可以解决语法错误。

import java.util.ArrayList;
import java.util.List;

public class Foo {
    public static class Bar {
        public String sBar1, sBar2;

        public Bar(String sBar1, String sBar2) {
            this.sBar1 = sBar1;
            this.sBar2 = sBar2;
        }
    }

    String sFoo;
    List<Bar> bi;

    public Foo() {
        bi = new ArrayList<>();
    }

    public Foo(String sFoo, List<Bar> bi) {
        this.sFoo = sFoo;
        this.bi = bi;
    }

    public final void runFooBar(String sFoo, Bar... barArgs) {
        this.sFoo = sFoo;
        for (Bar x : barArgs) {
            System.out.println(x.sBar1 + ":" + x.sBar2);
        }
    }

    public static void main(String[] args) {
        Foo fi = new Foo();
        fi.runFooBar("foo 1", new Bar("1 sBar1", "1 sBar2"), new Bar("2 sBar1", "2 sBar2"));

    }//end main
}//end class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM