// 不可实例化工具类
public final class MyUtils {
private MyUtils() {
throw new AssertionError("No " + MyUtils.class.getName() + " instances for you !");
}
}
// 编译报错 - MyUtils() 在 com.jiafupeng.controller.rest.MyUtils 中是 private 访问控制
MyUtils myUtils = new MyUtils();
Class<MyUtils> adminClass = MyUtils.class;
Constructor<?>[] declaredConstructors = adminClass.getDeclaredConstructors();
Constructor<?> c = declaredConstructors[0];
c.setAccessible(true);// 使其能访问到private构造方法
Object o = c.newInstance();
System.out.println(o);
// 运行报错
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.jiafupeng.controller.rest.UserController.main(UserController.java:59)
Caused by: java.lang.AssertionError: No com.jiafupeng.controller.rest.MyUtils instances for you !
at com.jiafupeng.controller.rest.MyUtils.<init>(MyUtils.java:11)
... 5 more
/**
* This class consists of {@code static} utility methods for operating
* on objects. These utilities include {@code null}-safe or {@code
* null}-tolerant methods for computing the hash code of an object,
* returning a string for an object, and comparing two objects.
*
* @since 1.7
*/
public final class Objects {
private Objects() {
throw new AssertionError("No java.util.Objects instances for you!");
}
...
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有