简体   繁体   中英

How to set a specific return type to a method in Java

So I have a class called Person

I can easily do something like

Person getPerson(){ return new Person(); }

But instead of using the 'Person' I want to declare my own class as a return type

Class<?> personClass = Class.forName("Person");
personClass getPerson() { return new Person(); }

Is this possible?

Your design is almost certainly wrong if you want to implement this, but yes, it's possible.

Object getThing(String className) throws Exception
{
    return Class.forName(className).getConstructor().newInstance();
}

You'll have to cast the result.

If you want Person class object (I mean, Class<Person> ), you can just use Person.class or personInstance.getClass() .

Also, if you want a custom method that will return it, then you can use:

public Class<Person> getPersonClass() {
    return Person.class;
}

But it is almost pointless, because you can just call Person.class . Beware, also, that Person.class is evaluated in compile time, and Class.forName("...") - in runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM