java 获取参数泛型类型
import java.lang.reflect.ParameterizedType; public abstract class SampleObjectCallBack<T> { private Class<T> clazz; @SuppressWarnings("unchecked") public SampleObjectCallBack() { ParameterizedType type = (ParameterizedType) this.getClass() .getGenericSuperclass(); this.clazz = (Class<T>) type.getActualTypeArguments()[0]; } public abstract void onSuccess(T t); public abstract void onError(int error, String msg); public Class<T> getClazz() { return clazz; } }
用于(接口)回调中获取其泛型的类型。
.................
..............
String url = text; HMChatManager.getInstance().postByURL(url, null, new SampleObjectCallBack<Friend>() { @Override public void onSuccess(Friend t) { if (t != null) { Log.d("", "" + t.toString()); Intent intent = new Intent(QRActivity.this, FriendDetailActivity.class); intent.putExtra(FriendDetailActivity.KEY_ENTER, FriendDetailActivity.ENTER_SEARCH); intent.putExtra(FriendDetailActivity.KEY_DATA, t); startActivity(intent); finish(); } } @Override public void onError(int error, String msg) { if (error == 200) { ToastUtil.show(getApplicationContext(), "你扫描的用户不存在"); finish(); } } });
.......
.......