Check if a member is inheritable in Java
Description
The following code shows how to check if a member is inheritable.
Example
// ww w. j a v a2 s. c om
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] argv){
Method[] methods = String.class.getMethods();
for (int idx = 0; idx < methods.length; idx++) {
System.out.println(isInheritable(String.class.getPackage(), methods[idx]));
}
}
public static boolean isInheritable(Package pack, Member member) {
if (pack == null)
return false;
if (member == null)
return false;
int modifiers = member.getModifiers();
if (Modifier.isPublic(modifiers))
return true;
if (Modifier.isProtected(modifiers))
return true;
if (!Modifier.isPrivate(modifiers) && pack.equals(member.getDeclaringClass().getPackage()))
return true;
return false;
}
}
The code above generates the following result.