Close

Java Reflection - Method.canAccess() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Method

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.Methodjava.lang.reflect.MethodLogicBig

Method:

public final boolean canAccess(Object obj)

This method returns true if the caller can access this method.


Examples


package com.logicbig.example.method;

import java.lang.reflect.Method;

public class CanAccessExample {
private static class Test {
private void doSomething() {
}
}

public static void main(String... args) throws NoSuchMethodException {
Method m = Test.class.getDeclaredMethod("doSomething");
Test test = new Test();
System.out.println(m.canAccess(test));
boolean b = m.trySetAccessible();
System.out.println(b);
System.out.println(m.canAccess(test));
}
}

Output

false
true
true




package com.logicbig.example.method;

import java.lang.reflect.Method;

public class CanAccessExample2 {
public static class Test {
public void doSomething() {
}
}

public static void main(String... args) throws NoSuchMethodException {
Method m = Test.class.getDeclaredMethod("doSomething");
boolean b = m.canAccess(new Test());
System.out.println(b);

System.out.println(m.isAccessible());
}
}

Output

true
false




See Also