如何从通用方法中调用非泛型方法:
class Test {
...
public <T> int someFunction1(T someParam) {
return someFunction2(someParam);
}
public int someFunction2(String someParam) {
return 1;
}
public int someFunction2(Integer someParam) {
return 1;
}
}
Test t = new Test;
t.someFunction1(new String("1"));
t.someFunction1(new Integer(5));
是否可以在编译时而不是在运行时执行此操作?
答案 0 :(得分:4)
编译器无法确定someParam
中的someFunction1
是String
还是Integer
。这样的事情会起作用:
public <T extends String> int someFunction1(T someParam) {
return someFunction2(someParam);
}
public int someFunction2(String someParam) {
return 1;
}
如果您希望它为String
/ Integer
,您需要创建一些数据类型或创建someFunction1
的重载定义T
绑定到Integer
}
或者只是一些“丑陋”演员:
public <T> int someFunction1(T someParam) {
if (someParam instanceof Integer)
return someFunction2((Integer) someParam);
else if (someParam instanceof String)
return someFunction2((String) someParam);
else throw new IllegalArgumentException("Expected String or Integer")
}
答案 1 :(得分:3)
您需要检查参数类型并根据其类型显式转换并调用正确的方法:
public <T> int someFunction1(T someParam) {
if (someParam instanceof Integer)
return someFunction2((Integer)someParam);
else if (someParam instanceof String)
return someFunction2((String)someParam);
else
throw new InvalidArgumentException("Unexepected type: "+someParam.getClass());
}
答案 2 :(得分:0)
仿制药不添加任何东西。您可以(并且应该)从方法中删除类型变量而不更改行为:
public int someFunction1(Object someParam) {
然后应用其他答案中提出的if/else
instanceof
个链之一。
答案 3 :(得分:0)
只有当参数始终为字符串或整数
时,此答案才有效package com.example.android.courtcounter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Displays the given score for Team A.
*/
public void displayForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score);
scoreView.setText(String.valueOf(score));
}
}