Heim > Fragen und Antworten > Hauptteil
private String getMainTitle(List<String> bs){
for(String b:bs){
if (b.equals("GOOD"){
return "string";
}
}
return null;
}
private String getMainTitle(String b){
if (b.equals("GOOD"){
return "string";
}
return null;
}
public String getTitleFromString(String b){
return getMainTitle(b);
}
public String getTitleFromList(List<String> bs){
return getMainTitle(bs);
}
請問怎样在JAVA寫一個含未知類的參數的方法?
希望寫一個方法能替代getTitleFromString和getTitleFromList , 比如:
public String getTitleFromList(T<?> t){
return getMainTitle(t);
}
但我的語法有誤, 請問該怎样改寫?
阿神2017-04-18 10:53:05
public String <T> getMainTitle(T obj){
if(Map.class.isAssignableFrom(obj.getClass())){
((Map<?, ?>) data).forEach((k, v) -> {
if (v.equals("GOOD")) {
return "string";
}
});
} else if(Vector.class.isAssignableFrom(obj.getClass())){
for(String b:bs){
if (b.equals("GOOD")) {
return "string";
}
}
} else if ( b.equals("GOOD") ){
return "string";
}
return null;
}
阿神2017-04-18 10:53:05
private String getMainTitle(List<String> bs){
for(String b:bs){
if (b.equals("GOOD")) {
return "string";
}
}
return null;
}
private String getMainTitle(String b){
if (b.equals("GOOD")) {
return "string";
}
return null;
}
public String getTitleFrom(String b){
return getMainTitle(b);
}
public String getTitleFrom(List<String> bs){
return getMainTitle(bs);
}
ringa_lee2017-04-18 10:53:05
这样可行
private <T> T getMainTitle(T t){
if (t.equals("GOOD")){
return (T)"string";
}
return null;
}
public <T> T getTitleFromString(T t){
return getMainTitle(t);
}
怪我咯2017-04-18 10:53:05
// Object...objs相当一个Object[]数组,用来当做参数,表示有未知个参数传入,甚至可以不传参!
public String getMainTitle(Object...objs) {
for (Object obj : objs) {
if(obj.toString().equals("GOOD")){
return "string";
}
}
return null;
}
// 使用
public void static main(String[] args) {
getMainTitle();
getMainTitle("sdfds", "Goods", "GOOD");
getMainTitle(true, "GOOD");
getMainTitle(111,1111);
}