I tried to create a object from anonymous class in run time.but when i tried to call newInstance()
it throw an error called java.lang.NoSuchMethodException
.
Anonymous Class Implementation
public enum Delegates implements Supplier<User> {
ADMINUSER {
@Override
public User get() {
return new User(){
@Override
public String getRole() {
return "Admin";
}
};
}
}
User.Java
public class User{
public String getRole() {
return "Student";
}
}
Create Instance from Runtime
Delegates.ADMINUSER.get().getClass().newInstance()
throw an error called
java.lang.NoSuchMethodException: com.users.Delegates$4$1.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
... 2 more
Please let me know how to create a instance from anonymous class in run time.
要创建实例,只需使用您的get方法:
User user = Delegates.ADMINUSER.get();
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.