如何访问泛型类参数中的属性/方法

时间:2017-11-22 16:21:58

标签: generics reflection kotlin

来自C#的Kotlin新手。

我正在尝试创建一个通过泛型接受可互换类对象的类。在类中,我想访问类中的属性值和调用方法。我认为这必须通过某种反射机制。通过Kotlin引用挖掘我一直在尝试将建议应用到我的代码中,但是我得到了一些神秘的错误。

感谢任何帮助。

public class Activity_Ascolta extends AppCompatActivity {

    final Context context = this;

    int flag = 0;

    final MediaPlayer [] mpList = new MediaPlayer[50];

    float volumecorrente = (float) (1 - (Math.log(100 - 50) / Math.log(100)));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //set content view AFTER ABOVE sequence (to avoid crash)
        this.setContentView(R.layout.layout_ascolta);

        setContentView(R.layout.layout_ascolta);

        final int MAX_VOLUME = 100;
        SeekBar seekBar = (SeekBar) findViewById(R.id.sb_volume);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                float volume = (float) (1 - (Math.log(MAX_VOLUME - progress) / Math.log(MAX_VOLUME)));
                mpList[flag].setVolume(volume, volume);
                volumecorrente = volume;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        TextView tv_sopra = (TextView) findViewById(R.id.tv_ascolta_1);
        TextView tv_sotto = (TextView) findViewById(R.id.tv_ascolta_2);
        TextView tv_apprezza = (TextView) findViewById(R.id.tv_ascolta_3);

        SharedPreferences scelta_lingua = getSharedPreferences("pref_lingua", context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = scelta_lingua.edit();
        String lingua_corrente = scelta_lingua.getString("pref_lingua", "");

        if (lingua_corrente.compareTo("italiano") == 0) {
            tv_sopra.setText("ASCOLTA");
            tv_sotto.setText("LA MUSICA");
            tv_apprezza.setText("APPREZZA LE DIFFERENZE DI OGNI CUFFIA");
        } else if (lingua_corrente.compareTo("inglese") == 0) {
            tv_sopra.setText("LISTEN");
            tv_sotto.setText("TO THE MUSIC");
            tv_apprezza.setText("APPRECIATES THE DIFFERENCES OF EACH HEADSET");
        }

        ImageButton returnHome = (ImageButton) findViewById(R.id.img_btt_return_home_ascolto);
        returnHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mpList != null) {mpList[flag].release();}

                final Intent toHome = new Intent(Activity_Ascolta.this, Activity_Home.class);
                startActivity(toHome);

            }
        });

        ImageButton playMusic = (ImageButton) findViewById(R.id.img_btt_play_music);
        playMusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                /*final Intent toMediaPlayer = new Intent(Activity_Ascolta.this,Activity_MediaPlayer.class);
                startActivity(toMediaPlayer);*/

                if (mpList != null) {mpList[flag].release();}

                //generate random number
                Random randomGenerator = new Random();
                int randomInt = randomGenerator.nextInt(mpList.length);

                Log.e("Random" , String.valueOf(randomInt));
                mpList[randomInt].start();
                mpList[randomInt].setVolume(volumecorrente,volumecorrente);
                flag = randomInt;

            }
        });
    }

    @Override
    protected void onStart () {

        super.onStart();
        loadingSongs();

    }

    public void loadingSongs (){

        mpList [0] = MediaPlayer.create(Activity_Ascolta.this, R.raw.a24k_magic);
        mpList [1] = MediaPlayer.create(Activity_Ascolta.this, R.raw.abbaon_fat_tracks);
        mpList [2] = MediaPlayer.create(Activity_Ascolta.this, R.raw.after_the_afterlife);
        mpList [3] = MediaPlayer.create(Activity_Ascolta.this, R.raw.amalia);
        mpList [4] = MediaPlayer.create(Activity_Ascolta.this, R.raw.amerimacka);
        mpList [5] = MediaPlayer.create(Activity_Ascolta.this, R.raw.angels);
        mpList [6] = MediaPlayer.create(Activity_Ascolta.this, R.raw.anymore);
        mpList [7] = MediaPlayer.create(Activity_Ascolta.this, R.raw.baby_gurl_original_mix);
        mpList [8] = MediaPlayer.create(Activity_Ascolta.this, R.raw.back_home);
        mpList [9] = MediaPlayer.create(Activity_Ascolta.this, R.raw.beautiful_escape_feat_zak_a);
        mpList [10] = MediaPlayer.create(Activity_Ascolta.this, R.raw.better_with_you);
        mpList [11] = MediaPlayer.create(Activity_Ascolta.this, R.raw.black_jeans_vocal_mix);
        mpList [12] = MediaPlayer.create(Activity_Ascolta.this, R.raw.body_music);
        mpList [13] = MediaPlayer.create(Activity_Ascolta.this, R.raw.born_to_run);
        mpList [14] = MediaPlayer.create(Activity_Ascolta.this, R.raw.brother_john);
        mpList [15] = MediaPlayer.create(Activity_Ascolta.this, R.raw.bye_bye_boy);
        mpList [16] = MediaPlayer.create(Activity_Ascolta.this, R.raw.cloud_9);
        mpList [17] = MediaPlayer.create(Activity_Ascolta.this, R.raw.daddy_s_groove);
        mpList [18] = MediaPlayer.create(Activity_Ascolta.this, R.raw.don_t_go);
        mpList [19] = MediaPlayer.create(Activity_Ascolta.this, R.raw.down_the_road_irfane_remix);
        mpList [20] = MediaPlayer.create(Activity_Ascolta.this, R.raw.down_to_the_sound);
        mpList [21] = MediaPlayer.create(Activity_Ascolta.this, R.raw.eye_of_the_tiger);
        mpList [22] = MediaPlayer.create(Activity_Ascolta.this, R.raw.fly_feat_kelsey);
        mpList [23] = MediaPlayer.create(Activity_Ascolta.this, R.raw.glad_edit);
        mpList [24] = MediaPlayer.create(Activity_Ascolta.this, R.raw.i_can_see_clearly_now);
        mpList [25] = MediaPlayer.create(Activity_Ascolta.this, R.raw.i_don_t_wanna_live_forever_fifty_shades_darker);
        mpList [26] = MediaPlayer.create(Activity_Ascolta.this, R.raw.jump);
        mpList [27] = MediaPlayer.create(Activity_Ascolta.this, R.raw.kill_it_tonight_feat_ice_mc);
        mpList [28] = MediaPlayer.create(Activity_Ascolta.this, R.raw.kindling_for_the_master_majo);
        mpList [29] = MediaPlayer.create(Activity_Ascolta.this, R.raw.lady_divine);
        mpList [30] = MediaPlayer.create(Activity_Ascolta.this, R.raw.life_round_here);
        mpList [31] = MediaPlayer.create(Activity_Ascolta.this, R.raw.make_you_feel);
        mpList [32] = MediaPlayer.create(Activity_Ascolta.this, R.raw.melt_away_original_mix);
        mpList [33] = MediaPlayer.create(Activity_Ascolta.this, R.raw.midnight_feast);
        mpList [34] = MediaPlayer.create(Activity_Ascolta.this, R.raw.palace_posy);
        mpList [35] = MediaPlayer.create(Activity_Ascolta.this, R.raw.pirates_of_samba_oxio_radio);
        mpList [36] = MediaPlayer.create(Activity_Ascolta.this, R.raw.pledge_allegiance_the_rimsho);
        mpList [37] = MediaPlayer.create(Activity_Ascolta.this, R.raw.queen_of_the_night_feat_nik);
        mpList [38] = MediaPlayer.create(Activity_Ascolta.this, R.raw.set_me_free_feat_alexandra_p);
        mpList [39] = MediaPlayer.create(Activity_Ascolta.this, R.raw.sister_welcome);
        mpList [40] = MediaPlayer.create(Activity_Ascolta.this, R.raw.space_walk);
        mpList [41] = MediaPlayer.create(Activity_Ascolta.this, R.raw.the_sweetest);
        mpList [42] = MediaPlayer.create(Activity_Ascolta.this, R.raw.to_get_up_with_you_remix);
        mpList [43] = MediaPlayer.create(Activity_Ascolta.this, R.raw.towers_feat_szjerdene);
        mpList [44] = MediaPlayer.create(Activity_Ascolta.this, R.raw.traveling_miles);
        mpList [45] = MediaPlayer.create(Activity_Ascolta.this, R.raw.tricks_main_vocal_original);
        mpList [46] = MediaPlayer.create(Activity_Ascolta.this, R.raw.ugly_brotha_real_nices_pri);
        mpList [47] = MediaPlayer.create(Activity_Ascolta.this, R.raw.wanting_you);
        mpList [48] = MediaPlayer.create(Activity_Ascolta.this, R.raw.we_just_couldnt_say_goodbye);
        mpList [49] = MediaPlayer.create(Activity_Ascolta.this, R.raw.you_d_be_so_nice_to_come_home);

        return ;
    }
}

在修改访问泛型类属性之后,代码看起来像这样,println中有错误:

Error:(35, 20) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
@InlineOnly public operator inline fun <T> Lazy<T1?>.getValue(thisRef: Any?, property: KProperty<*>): T1? defined in kotlin
@InlineOnly public operator inline fun <V, V1 : T1?> Map<in String, T1?>.getValue(thisRef: Any?, property: KProperty<*>): T1? defined in kotlin.collections
@SinceKotlin public fun <K, V> Map<Class<T1>, T1?>.getValue(key: Class<T1>): T1? defined in kotlin.collections
@JvmName @InlineOnly public operator inline fun <V> MutableMap<in String, in T1?>.getValue(thisRef: Any?, property: KProperty<*>): T1? defined in kotlin.collections
Error:(75, 20) Kotlin: Expression in a class literal has a nullable type 'T1?', use !! to make the type non-nullable
Error:(75, 35) Kotlin: Type parameter bound for T in val <T : Any> KClass<T>.memberProperties: Collection<KProperty1<T, *>>
 is not satisfied: inferred type CapturedTypeConstructor(out T1?) is not a subtype of Any

open class Base<T1, T2> (@Autowired var t2: T2) {

    @Autowired var request: T1? = null

  inline fun <reified T1: Any> retrieveClass(): T1? {
    return request.getValue(T1::class.java)
  }

  fun endpoint(
    @ApiParam(value = "Options", required = true) @Valid @RequestBody
        body: T1
    ): ResponseEntity<MyResponse> {
        type1 = body
        val obj = retrieveClass()
        for (prop in obj::class.memberProperties) {
           println("${prop.name} = ${prop.get(obj)}")
        }
        val usefulResult = obj.usefulMethod()
    }
}

0 个答案:

没有答案