Close

Java Reflection - Constructor.canAccess() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Constructor

java.lang.Objectjava.lang.Objectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AnnotatedElementAnnotatedElementjava.lang.reflect.Executablejava.lang.reflect.Executablejava.lang.reflect.MemberMemberjava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.Constructorjava.lang.reflect.ConstructorLogicBig

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);
}
}

Output

true




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);
}
}

Output

false
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);
}
}

Output

true




See Also