Generic class parameters in Java

So I pass activities and intentions in my Android application to handle threads (I'm sure there's a better example because my code starts to get annoying spaghetti - usually my logo doesn't do the right thing)

But anyway, I try to do something like this:

public class SomeCoolActivity extends Activity {
    private class DoSoMetaskThatInvolvesEitherTheNetworkOrASleepStatementWithoutScrewingUpTheUiThread extends AsyncTask<Void,Void,Void> {
        @Override
        protected Void doInBackground(Void... params) {
            // Do something useful on a non-UI thread...
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Now that's done,I need to progress to the next activity. If I do that here,// I will get errors. So instead,I will call a method on my parent activity class:
            loadNextActivity(NextActivity.class);
        }
    }

    protected void loadNextActivity(Class<Activity> activityToLoad) {
        startActivity(new Intent(this,activityToLoad));
    }
}

But it didn't work because it told me there was a mistake, that

NextActivity.class

Not an activity Yes, obviously it's not exactly the same class, but people expect me to pass any class derived from activity (including nextactivity), but not any class that doesn't (if I define loadnextactivity, it actually works normally, such as

protected void loadNextActivity(Class<?> activityToLoad)

But that's not ideal, because I can pass anything I want, maybe something that isn't active... After all, it's Java, not ruby Besides, if it only allows me to pass one class... What is good?

What should I do?

Solution

You can write wildcards, such as:

protected void loadNextActivity(Class<? extends Activity> activityToLoad)

Use class This is a bad practice You don't know the exact type of class token Well, try to define the global behavior for my method, as I wrote above, using wildcards

By the way, make sure you add it to manifest Each activity in the XML file, for example:

<activity android:name=".com.bla.bla.YourOtherActivity" />
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>