The key is to use visibleWhen part properly. This is an example of a command showing in Project Explorer which is visible only when a Java method or class is selected:
<menuContribution
locationURI="popup:org.eclipse.ui.navigator.ProjectExplorer#PopupMenu">
<command
commandId="__your.command.id__"
id="your.contribution.id"
label="Some Label"
style="push">
<visibleWhen
checkEnabled="false">
<iterate
ifEmpty="false"
operator="and">
<or>
<instanceof
value="org.eclipse.jdt.core.IType">
</instanceof>
<instanceof
value="org.eclipse.jdt.core.IMethod">
</instanceof>
</or>
</iterate>
</visibleWhen>
</command>
</menuContribution>
Don't forget to set commandId to something real.
You can find more info about property and selection testing here.