如果您对如何指示成员字段默认为@Nonnull?和字段默认为private感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解如何指示成员字段默认为@Nonnull?的各种细节,并对字段默认为pri
如果您对如何指示成员字段默认为@Nonnull?和字段默认为private感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解如何指示成员字段默认为@Nonnull?的各种细节,并对字段默认为private进行深入的分析,此外还有关于@Nonnull和Objects.requireNonNull有什么区别、android – 无法在looper.java中解析符号nonnull和notnull、android-在looper.java中解决nonnull和notnull符号的问题、android.annotation.NonNull的实例源码的实用技巧。
本文目录一览:- 如何指示成员字段默认为@Nonnull?(字段默认为private)
- @Nonnull和Objects.requireNonNull有什么区别
- android – 无法在looper.java中解析符号nonnull和notnull
- android-在looper.java中解决nonnull和notnull符号的问题
- android.annotation.NonNull的实例源码
如何指示成员字段默认为@Nonnull?(字段默认为private)
在过去的FindBugs版本中,可以使用@DefaultAnnotation(Nonnull.class)
或@DefaultAnnotationForFields(Nonnull.class)
指示包中的所有
字段
都应视为@Nonnull
。在FindBugs的(2.0)的当前版本@DefaultAnnotation
和@DefaultAnnotationForFields
已被弃用,并且我们都应该使用JSR-305来代替。但是,JSR-305似乎并未涵盖(现已弃用的)FindBugs注释所涵盖的所有内容。
该javadoc的确实表明了一些替代品:
@ParametersAreNonnullByDefault
。这(显然)仅适用于参数,不适用于成员字段。@CheckReturnValue
,当应用于类型或包时。同样,这不适用于成员字段。@TypeQualifierDefault
。也许这可以满足我的要求,但是我不了解它的工作原理,除了一些神秘的javadoc,我无法找到任何有关其用法或意图的文档或示例。我认为这将帮助我创建自己的注释,但是我可以确定所有工具(FindBugs,Eclipse等)都可以正确(甚至根本)解释这个新注释吗?
该javadoc中没有提供关于如何处理其弃用任何提示。
因此,使用FindBugs和/或JSR-305的当前版本,我应该如何指示某个包(甚至某个类)中的所有成员字段都应被视为@Nonnull
?可能吗?
答案1
小编典典我有一个类似的问题,发现以下内容似乎适用于findbugs(2.0.1-rc2)
使用以下注释定义创建一个Java文件
@Nonnull@TypeQualifierDefault(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface FieldsAreNonNullByDefault{}
类似地,强制所有方法的返回值都不为空
@Nonnull@TypeQualifierDefault(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface ReturnTypesAreNonNullByDefault{}
然后像往常一样注释该程序包。
我将以下内容用于测试(package-info.java)
@javax.annotation.ParametersAreNonnullByDefault@com.habit.lib.lang.FieldsAreNonNullByDefault@com.habit.lib.lang.ReturnTypesAreNonNullByDefaultpackage com.mypackagename.subpkg;
@Nonnull和Objects.requireNonNull有什么区别
以下两个代码段之间有什么区别?
public Integer getId(@Nonnull SomeObject obj){ // do some stuff return id;}public Integer getId(SomeObject obj){ Objects.requireNonNull(SomeObject, "SomeObject is null"); // do some stuff return id;}
它们之间有什么显着差异。在这些情况下进行空值检查的正确方法是什么。
答案1
小编典典两者是互补的:@Nonnull
注解记录了obj
必须为非空的事实,而Objects.requireNonNull
调用则确保obj
运行时该值不为空。
您应该将两者结合起来,如下所示:
public Integer getId(@Nonnull SomeObject obj){ Objects.requireNonNull(SomeObject, "SomeObject is null"); // do some stuff return id;}
有关的文档@Nonnull
可以在这里找到:
可选的类型注释不能替代运行时验证
在类型注释之前,用于描述可为空性或范围之类的内容的主要位置位于javadoc中。通过类型注释,此通信以一种编译时验证的方式进入字节码。
您的代码仍应执行运行时验证。
android – 无法在looper.java中解析符号nonnull和notnull
package android.os; import android.support.annotation.NonNull; import android.support.annotation.Nullable;
我添加了以下依赖项:
dependencies { compile group: 'com.google.code.findbugs',name: 'jsr305',version: '3.0.0' compile 'com.android.support:multidex:1.0.1' compile filetree(include: ['*.jar'],dir: 'libs') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:support-v4:23.1.1' compile 'com.android.support:design:23.1.1' compile 'com.parse:parse-android:1.12.0' compile filetree(include: '*.jar',dir: 'libs') compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.android.support:support-annotations:23.1.1' }
解决方法
compile 'com.android.support:support-annotations:+'
另外,验证这一点
转到文件 – >设置 – >搜索“可空”并验证这些设置.
android-在looper.java中解决nonnull和notnull符号的问题
我正在开发一个Android应用程序,请帮助我解决依赖项错误.
package android.os;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
我添加了以下依赖项:
dependencies {
compile group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.0'
compile 'com.android.support:multidex:1.0.1'
compile filetree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.parse:parse-android:1.12.0'
compile filetree(include: '*.jar', dir: 'libs')
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.android.support:support-annotations:23.1.1'
}
解决方法:
在您的依赖项中添加以下内容
compile 'com.android.support:support-annotations:+'
另外,验证一下
转到文件->设置->搜索“可为空”并验证这些设置.
android.annotation.NonNull的实例源码
/** * A special variation to launch an activity only if a new activity * instance is needed to handle the given Intent. In other words,this is * just like {@link #startActivityForResult(Intent,int)} except: if you are * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag,or * singleTask or singletop * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},* and the activity * that handles <var>intent</var> is the same as your currently running * activity,then a new instance is not needed. In this case,instead of * the normal behavior of calling {@link #onNewIntent} this function will * return and you can handle the Intent yourself. * * <p>This function can only be called from a top-level activity; if it is * called from a child activity,a runtime exception will be thrown. * * @param intent The intent to start. * @param requestCode If >= 0,this code will be returned in * onActivityResult() when the activity exits,as described in * {@link #startActivityForResult}. * @param options Additional options for how the Activity should be started. * See {@link android.content.Context#startActivity(Intent,Bundle) * Context.startActivity(Intent,Bundle)} for more details. * * @return If a new activity was launched then true is returned; otherwise * false is returned and you must handle the Intent yourself. * * @see #startActivity * @see #startActivityForResult */ public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,int requestCode,@Nullable Bundle options) { if (mParent == null) { int result = ActivityManager.START_RETURN_INTENT_TO_CALLER; try { Uri referrer = onProvideReferrer(); if (referrer != null) { intent.putExtra(Intent.EXTRA_REFERRER,referrer); } intent.migrateExtraStreamToClipData(); intent.preparetoLeaveProcess(this); result = ActivityManagerNative.getDefault() .startActivity(mMainThread.getApplicationThread(),getBasePackageName(),intent,intent.resolveTypeIfNeeded(getContentResolver()),mToken,mEmbeddedID,requestCode,ActivityManager.START_FLAG_ONLY_IF_NEEDED,null,options); } catch (remoteexception e) { // Empty } Instrumentation.checkStartActivityResult(result,intent); if (requestCode >= 0) { // If this start is requesting a result,we can avoid making // the activity visible until the result is received. Setting // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the // activity hidden during this time,to avoid flickering. // This can only be done when a result is requested because // that guarantees we will get information back when the // activity is finished,no matter what happens to it. mStartedActivity = true; } return result != ActivityManager.START_RETURN_INTENT_TO_CALLER; } throw new UnsupportedOperationException( "startActivityIfNeeded can only be called from a top-level activity"); }
/** * Returns class name for this activity with the package prefix removed. * This is the default name used to read and write settings. * * @return The local class name. */ @NonNull public String getLocalClassName() { final String pkg = getPackageName(); final String cls = mComponent.getClassName(); int packageLen = pkg.length(); if (!cls.startsWith(pkg) || cls.length() <= packageLen || cls.charat(packageLen) != '.') { return cls; } return cls.substring(packageLen+1); }
/** * This is called when a child activity of this one calls its * finishActivity(). * * @param child The activity making the call. * @param requestCode Request code that had been used to start the * activity. */ public void finishActivityFromChild(@NonNull Activity child,int requestCode) { try { ActivityManagerNative.getDefault() .finishsubactivity(mToken,child.mEmbeddedID,requestCode); } catch (remoteexception e) { // Empty } }
@Override public Object getSystemService(@ServiceName @NonNull String name) { if (getBaseContext() == null) { throw new IllegalStateException( "System services not available to Activities before onCreate()"); } if (WINDOW_SERVICE.equals(name)) { return mWindowManager; } else if (SEARCH_SERVICE.equals(name)) { ensureSearchManager(); return mSearchManager; } return super.getSystemService(name); }
/** * Create a new PendingIntent object which you can hand to others * for them to use to send result data back to your * {@link #onActivityResult} callback. The created object will be either * one-shot (becoming invalid after a result is sent back) or multiple * (allowing any number of results to be sent through it). * * @param requestCode Private request code for the sender that will be * associated with the result data when it is returned. The sender can not * modify this value,allowing you to identify incoming results. * @param data Default data to supply in the result,which may be modified * by the sender. * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},* {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},* {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},* {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},* or any of the flags as supported by * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts * of the intent that can be supplied when the actual send happens. * * @return Returns an existing or new PendingIntent matching the given * parameters. May return null only if * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been * supplied. * * @see PendingIntent */ public PendingIntent createPendingResult(int requestCode,@NonNull Intent data,@PendingIntent.Flags int flags) { String packageName = getPackageName(); try { data.preparetoLeaveProcess(this); IIntentSender target = ActivityManagerNative.getDefault().getIntentSender( ActivityManager.INTENT_SENDER_ACTIVITY_RESULT,packageName,mParent == null ? mToken : mParent.mToken,new Intent[] { data },flags,UserHandle.myUserId()); return target != null ? new PendingIntent(target) : null; } catch (remoteexception e) { // Empty } return null; }
/** * Special version of starting an activity,for use when you are replacing * other activity components. You can use this to hand the Intent off * to the next Activity that can handle it. You typically call this in * {@link #onCreate} with the Intent returned by {@link #getIntent}. * * @param intent The intent to dispatch to the next activity. For * correct behavior,this must be the same as the Intent that started * your own activity; the only changes you can make are to the extras * inside of it. * @param options Additional options for how the Activity should be started. * See {@link android.content.Context#startActivity(Intent,Bundle)} for more details. * * @return Returns a boolean indicating whether there was another Activity * to start: true if there was a next activity to start,false if there * wasn't. In general,if true is returned you will then want to call * finish() on yourself. */ public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent,@Nullable Bundle options) { if (mParent == null) { try { intent.migrateExtraStreamToClipData(); intent.preparetoLeaveProcess(this); return ActivityManagerNative.getDefault() .startNextMatchingActivity(mToken,options); } catch (remoteexception e) { // Empty } return false; } throw new UnsupportedOperationException( "startNextMatchingActivity can only be called from a top-level activity"); }
/** * Convenience for calling * {@link android.view.Window#getLayoutInflater}. */ @NonNull public LayoutInflater getLayoutInflater() { return getwindow().getLayoutInflater(); }
/** * Requests permissions to be granted to this application. These permissions * must be requested in your manifest,they should not be granted to your app,* and they should have protection level {@link android.content.pm.PermissionInfo * #PROTECTION_DANGEROUS dangerous},regardless whether they are declared by * the platform or a third-party app. * <p> * normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_norMAL} * are granted at install time if requested in the manifest. Signature permissions * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at * install time if requested in the manifest and the signature of your app matches * the signature of the app declaring the permissions. * </p> * <p> * If your app does not have the requested permissions the user will be presented * with UI for accepting them. After the user has accepted or rejected the * requested permissions you will receive a callback on {@link * #onRequestPermissionsResult(int,String[],int[])} reporting whether the * permissions were granted or not. * </p> * <p> * Note that requesting a permission does not guarantee it will be granted and * your app should be able to run without having this permission. * </p> * <p> * This method may start an activity allowing the user to choose which permissions * to grant and which to reject. Hence,you should be prepared that your activity * may be paused and resumed. Further,granting some permissions may require * a restart of you application. In such a case,the system will recreate the * activity stack before delivering the result to {@link * #onRequestPermissionsResult(int,int[])}. * </p> * <p> * When checking whether you have a permission you should use {@link * #checkSelfPermission(String)}. * </p> * <p> * Calling this API for permissions already granted to your app would show UI * to the user to decide whether the app can still hold these permissions. This * can be useful if the way your app uses data guarded by the permissions * changes significantly. * </p> * <p> * You cannot request a permission if your activity sets {@link * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to * <code>true</code> because in this case the activity would not receive * result callbacks including {@link #onRequestPermissionsResult(int,int[])}. * </p> * <p> * The <a href="http://developer.android.com/samples/RuntimePermissions/index.html"> * RuntimePermissions</a> sample app demonstrates how to use this method to * request permissions at run time. * </p> * * @param permissions The requested permissions. Must me non-null and not empty. * @param requestCode Application specific request code to match with a result * reported to {@link #onRequestPermissionsResult(int,int[])}. * Should be >= 0. * * @see #onRequestPermissionsResult(int,int[]) * @see #checkSelfPermission(String) * @see #shouldShowRequestPermissionRationale(String) */ public final void requestPermissions(@NonNull String[] permissions,int requestCode) { if (mHasCurrentPermissionsRequest) { Log.w(TAG,"Can reqeust only one set of permissions at a time"); // dispatch the callback with empty arrays which means a cancellation. onRequestPermissionsResult(requestCode,new String[0],new int[0]); return; } Intent intent = getPackageManager().buildrequestPermissionsIntent(permissions); startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX,null); mHasCurrentPermissionsRequest = true; }
/** * Enable or disable virtual reality (VR) mode for this Activity. * * <p>VR mode is a hint to Android system to switch to a mode optimized for VR applications * while this Activity has user focus.</p> * * <p>It is recommended that applications additionally declare * {@link android.R.attr#enableVrMode} in their manifest to allow for smooth activity * transitions when switching between VR activities.</p> * * <p>If the requested {@link android.service.vr.VrListenerService} component is not available,* VR mode will not be started. Developers can handle this case as follows:</p> * * <pre> * String servicePackage = "com.whatever.app"; * String service; * * // Name of the component of the VrListenerService to start. * ComponentName serviceComponent = new ComponentName(servicePackage,serviceClass); * * try { * setVrModeEnabled(true,myComponentName); * } catch (PackageManager.NameNotFoundException e) { * List<ApplicationInfo> installed = getPackageManager().getInstalledApplications(0); * boolean isInstalled = false; * for (ApplicationInfo app : installed) { * if (app.packageName.equals(servicePackage)) { * isInstalled = true; * break; * } * } * if (isInstalled) { * // Package is installed,but not enabled in Settings. Let user enable it. * startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS)); * } else { * // Package is not installed. Send an intent to download this. * sentIntentToLaunchAppStore(servicePackage); * } * } * </pre> * * @param enabled {@code true} to enable this mode. * @param requestedComponent the name of the component to use as a * {@link android.service.vr.VrListenerService} while VR mode is enabled. * * @throws android.content.pm.PackageManager.NameNotFoundException if the given component * to run as a {@link android.service.vr.VrListenerService} is not installed,or has * not been enabled in user settings. * * @see android.content.pm.PackageManager#FEATURE_VR_MODE * @see android.content.pm.PackageManager#FEATURE_VR_MODE_HIGH_PERFORMANCE * @see android.service.vr.VrListenerService * @see android.provider.Settings#ACTION_VR_LISTENER_SETTINGS * @see android.R.attr#enableVrMode */ public void setVrModeEnabled(boolean enabled,@NonNull ComponentName requestedComponent) throws PackageManager.NameNotFoundException { try { if (ActivityManagerNative.getDefault().setVrMode(mToken,enabled,requestedComponent) != 0) { throw new PackageManager.NameNotFoundException( requestedComponent.flattenToString()); } } catch (remoteexception e) { // pass } }
关于如何指示成员字段默认为@Nonnull?和字段默认为private的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于@Nonnull和Objects.requireNonNull有什么区别、android – 无法在looper.java中解析符号nonnull和notnull、android-在looper.java中解决nonnull和notnull符号的问题、android.annotation.NonNull的实例源码的相关信息,请在本站寻找。
本文标签: