鉴于以下课程
abstract class SomeAbstractClass { abstract val name: String }
data class DataClass( override val name: String ) : SomeAbstractClass()
class NoDataClass( override val name: String ) : SomeAbstractClass()
对于SomeAbstractClass
的任何实例,我可以在不依赖类型检查的情况下确定它是data class吗?
一些背景知识:这似乎是将继承和数据类组合到我的最佳方式,as suggested in a different answer。现在,在SomeAbstractClass
的初始化块中,我想抛出一个异常,以防派生类型不是一个数据类,以确保派生类型的'正确'(不可变)实现。
答案 0 :(得分:0)
使用reflection,可以使用您要调查的实例上的import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.MyViewHolder> {
private ArrayList<String> data;
private Context mContext;
public ReviewAdapter(Context mContext, ArrayList<String> data) {
this.mContext=mContext;
this.data = data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_row, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.txtPlayerName.setText(data.get(position));
holder.txtRowNumber.setText(String.valueOf(position + 1));
}
@Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, TextWatcher {
EditText txtPlayerName;
TextView txtRowNumber;
Button btnRemoveRow;
public MyViewHolder(View view) {
super(view);
txtPlayerName = itemView.findViewById(R.id.listText);
txtRowNumber = itemView.findViewById(R.id.listIcon);
btnRemoveRow = itemView.findViewById(R.id.btnRemove);
btnRemoveRow.setOnClickListener(this);
txtPlayerName.addTextChangedListener(this);
}
@Override
public void onClick(View view) {
if (view == btnRemoveRow) {
data.remove(getAdapterPosition());
System.out.println("MyClickListener.onClick.pos: " + getAdapterPosition());
MainActivity.txtPlayers.setText(data.size() + " players");
notifyDataSetChanged();
}
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
data.set(getAdapterPosition(), s.toString());
//notifyItemChanged(getAdapterPosition());
}
@Override
public void afterTextChanged(Editable editable) {
}
}
}
语法获取Kotlin类描述(KClass)(在您的情况下,::class
in抽象类的初始化块)。这样,您就可以访问isData
:
如果此类是数据类,则为true。
但是,作为Oliver points out,数据类仍然可以包含this::class
个成员,因此您可能还需要检查是否所有成员变量(及其成员变量递归)都定义为var
确保所有派生类的不变性。