Java Reflection Java Java API
Class:
java.lang.reflect.Constructor
Method:
public final boolean canAccess(Object obj)
This method tests if the caller can access this constructor. For constructors obj must be null .
Examples
package com.logicbig.example.constructor;
import java.lang.reflect.Constructor;
public class CanAccessExample {
private CanAccessExample() {}
public static void main(String... args) throws NoSuchMethodException { Constructor<CanAccessExample> cons = CanAccessExample.class.getDeclaredConstructor(); boolean b = cons.canAccess(null); System.out.println(b); } }
Outputtrue
package com.logicbig.example.constructor;
import java.lang.reflect.Constructor;
public class CanAccessExample2 {
private static class Test { private Test() {} }
public static void main(String... args) throws NoSuchMethodException { Constructor<Test> cons = Test.class.getDeclaredConstructor(); boolean b = cons.canAccess(null); System.out.println(b);
boolean b1 = cons.trySetAccessible(); System.out.println(b1);
boolean b2 = cons.canAccess(null); System.out.println(b2); } }
Outputfalse true true
package com.logicbig.example.constructor;
import java.lang.reflect.Constructor;
public class CanAccessExample3 { public class Test { public Test() {} }
public static void main(String... args) throws NoSuchMethodException { //inner class has an implicit arg of outer class Constructor<Test> cons = Test.class.getDeclaredConstructor(CanAccessExample3.class); boolean b = cons.canAccess(null); System.out.println(b); } }
Outputtrue
|