0

I'm beginner in programming, I have so many classes like "AddItemBinding" (each of them, is matched to own xml layout).

public class MainViewHolder extends RecyclerView.ViewHolder{
    private AddItemBinding binding;
    public MainViewHolder(@NonNull View itemView) {
        super(itemView);
        binding = DataBindingUtil.bind(itemView);

    }
    public  void bindItemsModel(ViewModel viewModel) {
        binding.setModel(viewModels.get(getPosition()).viewDataSet);
    }
}

how to instantiate each class from its name stored in a String? like this:

private viewModels.get(getPosition).className binding;

className is a String field contains name of a class.

Context: I have designed a recyclerView. Each item of the recyclerView has its own layout. A data set list, passed to Adapter. these data includes the layouts addresses. I want to do this: in the Adapter class, for each item, reads layout address and corresponding binding class. name of the binding class, saved as a String.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 3
    Does this answer your question? [Is there a way to instantiate a class by name in Java?](https://stackoverflow.com/questions/9886266/is-there-a-way-to-instantiate-a-class-by-name-in-java) Did you remember to search before asking? – Ole V.V. Oct 23 '22 at 08:34
  • 2
    You cannot specify the type of a field as a variable like you did. Also your example `private viewModels.get(getPosition).className binding;` would not instantiate a new object, it is only a declaration. One solution could be generics, but you also mentioned something with "matched to own xml layout", maybe you can describe your overall goal you want to reach a bit more so we could think about proper solutions in a bigger picture. – cyberbrain Oct 23 '22 at 09:08
  • 1
    @OleV.V. I think this problem is actually bigger than just instatiating - the shown example code has no single place where a new object would be instantiated, I rather think this is either a problem to solve with generics or inheritance - and then maybe add reflection for instantiation on top, but maybe that's not necessary. – cyberbrain Oct 23 '22 at 09:12
  • I apologize for the ambiguity in the question. I have designed a recyclerView. each item of the recyclerView has own layout. a data set list, passed to Aadapter. these data includes the layouts addresses. I want to do this: in the Adapter class, for each item, reads layout address and corresponding binding class. name of the binding class, saved as a String. regards – Hadi Tayebifar Oct 23 '22 at 10:23
  • 1
    Better edit the question and add these explanations to it – HoRn Oct 23 '22 at 11:35
  • 1
    Thanks for giving precise context to enhance our understanding of your situation and your question. That helps. This time only I pasted the information into your question for you. In the future please do it yourself. – Ole V.V. Oct 23 '22 at 11:41

0 Answers0