How do you put the object class as a parameter?



  • public void onClick(View v) {
       switch (v.getId()) {
           case R.id.btnGallery:
               Intent intent = new Intent(this, ClassName1.class);
               startActivity(intent);
               break;
           case R.id.btnNew:
               intent = new Intent(this, ClassName2.class);
               startActivity(intent);
               break;
           case R.id.btnPrice:
               intent = new Intent(this, ClassName3.class);
               startActivity(intent);
               break;
           case R.id.btnCallBack:
               intent = new Intent(this, ClassName4.class);
               startActivity(intent);
               break;
           ...
       }
    }
    

    Since there is a variety of uniform work (objective activity), it would be desirable to optimize.

    Something like that:

    public void classUsing (String s) {
    
    Intent intent = new Intent(this, s.class);
    startActivity(intent);
    

    }

    @Override
    public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btnGallery:
    classUsing(ClassName1);
    break;
    case R.id.btnNew:
    classUsing(ClassName2);
    break;
    case R.id.btnPrice:
    classUsing(ClassName3);
    break;
    ...
    }
    }

    How do you put the class name in the form of an argument in another method and use it there?



  • <ИмяКласса>.class Type Class♪ You can pass the class as a parameter in this way:

    public void doSomething(Class clazz) {
        Intent i = new Intent(context, clazz);
    }
    

    Use of method:

    doSomething(Class1.class);
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2