I am trying to get a basic understanding of how to specify string encryption using the command -encryptstring in the file dexguard-project.txt. For example, I see
-encryptstrings "android.content.pm.PackageInfo",
"packageName",
"versionName",
"versionCode",
............ ,
"java.lang.String",
............
What does it mean?
There's good example of the options in the DexGuard docs {dexgaurd root}/samples/StringEncryption/dexguard-project.txt
Here's the ones I tend to use.
#encrypt a specific string in a class
-encryptstrings class com.example.HelloWorldActivity {
private static final java.lang.String MESSAGE;
}
#encrypt all strings in the class.
-encryptstrings class com.example.HelloWorldActivity
#specify the string itself, i.e any instance of "Hello world!" in your app.
-encryptstrings "Hello world!"
I do not know yet what the code means (in details) but it does not mean that precisely the specified strings should be encrypted. (Here by string I mean any one item in the list following the encryptstring command.) Rather, it means roughly that the specified instance variables in the Android class PackageInfo should be encrypted, also all the instances of the Java class String should be encrypted. I am still looking for a better understanding.
Related
While writing code for RecyclerView to get data I figured out there's a data class in Kotlin.
Following codes are taken from two different projects which are linked above.
#Serializable
data class MarsPhoto(
val id: String,
#SerialName(value = "img_src")
val imgSrc: String
)
class Contacts {
#SerializedName("country")
private val country:String? = null
fun getCountry():String?{
return country
}
}
I know that both classes are doing same job. So what does differentiate them? I also wonder in the MarsPhoto data class how they can get the id without declaring SerialName just the way they did for imgSrc. (I am just on the way to learning kotlin now, so I'm absolute beginner).
Basically for "data" class the compiler automatically derives the following members from all properties declared in the primary constructor:
equals()/hashCode() pair
toString() of the form "MarsPhoto(id=1, imgSrc=asdf)"
componentN() functions corresponding to the properties in their order of declaration.
copy()
You can read a lot more at enter link description here
On the SerializedName part of your question. if you are dealing with Gson lib by default it is using fields name as "SerializedName". And only if you want to use something different then field name, you can use SerializedName annotation and pass your custom value there. But usually, everybody just writes #SerializedName() with duplication of field names as value for every field.
It's a good idea if you are receiving and Serializing data from server from Json. Because Backend developers can use a bad keys in response, which you don't want to use in your code, so #SerializedName will be the only place where you will have to see this key, and you can name your fields however you like.
#Serializable used to mark class as serializable to disk or like into a file( alternative is Parcel able in android) special useful in case of process death or configuration changes and #SerializedName("country") used for json parsing when u receive the response from server
You get the id without #SerializedName because the JSON property field is the same as your variable name, but imgSrc and img_src is not. Still, even if they are the same, you should always use #SerializedName, because your variable names could be converted to random letters during code optimization, and obfuscation.
Currently class names are not being obfuscated. I need to find obfuscated package of specific class for use in reflection. Any ideas?
I can think of two approaches:
Read the obfuscated package name of the desired class from the <project_module>/build/outputs/mapping.txt and then write it to a file (asset for example) that you can add to the apk as in a new build step and read in your app. If you don't intend to add new classes/packages before (in lexicographical order) the one you wish to access you might even get away with picking the package name from mapping.txt and storing it in a String field somewhere in the app (but this is highly unstable/undesirable).
Declare a field containing the reference to the class you wish to access via reflection someplace where it's easy to find (the name and package of the Application subclass are not obfuscated because they are referenced in the manifest so that would be a good candidate) and then you simply use that reference:
public class YourApplication extends Application {
//...
public static Class<?> yourReflectiveClass = YourReflectiveClass.class;
}
And then you access that field and use it as you need:
//...
Field[] appFields = YourApplication.class.getDeclaredFields();
Field classField = null;
for (Field f : appFields) {
if (f.getType().equals(Class.class) {
classField = f;
break;
}
}
if (classField != null) {
Object classInstance = classField.get(null);
if (classInstance instanceof Class) {
Class<?> yourReflectiveClass = (Class) classInstance;
// yourReflectiveClass.getPackage().getName()
}
}
You might need to alter proguard-rules.pro to keep your new field(s) in the obfuscated variant.
Also note that this kind of defeats (at least partially) the purpose of obfuscation.
I found elegant solution. I store string constant into environment variable with value of needed class package. I can access any needed obfuscated data via static string key of environment variable. Even class name itself was obfuscated I would get always needed data. It is easy to access this data from any module in application since it is in environment variable.
static {
System.setProperty(Const.NEEDED_PACKAGE, NeededClass.class.getPackage()).getName());
}
I have a class that consists only of static member variables and static methods. Essentially, it is serving as a general-purpose utility class.
Is it bad practice for a class to contain only static member variables and static methods?
No, I don't think so at all. It is worse practice to have a class full of instance methods which don't actually depend on a particular instance. Making them static tells the user exactly how they are intended to be used. Additionally, you avoid unnecessary instantiations this way.
EDIT: As an afterthought, in general I think its nice to avoid using language features "just because", or because you think that that is the "Java way to do it". I recall my first job where I had a class full of static utility methods and one of the senior programmers told me that I wasn't fully harnessing the OO power of Java by making all of my methods "global". She was not on the team 6 months later.
As long as the class has no internal state and is essentially what is known as a leaf class (utility classes fall into this category), in other words it is independent of other classes. It is fine.
The Math class being a prime example.
Sounds reasonable.
Note: Classes that do this often have a private no-arg constructor just so that the compiler yields an error if a programmer tries to create an instance of the static class.
Static methods don't worry me much (except for testing).
In general, static members are a concern. For example, what if your app is clustered? What about start-up time -- what kind of initialization is taking place? For a consideration of these issues and more, check out this article by Gilad Bracha.
It's perfectly reasonable. In fact, in C# you can define a class with the static keyword specifically for this purpose.
Just don't get carried away with it. Notice that the java.lang.Math class is only about math functions. You might also have a StringUtilities class which contains common string-handling functions which aren't in the standard API, for example. But if your class is named Utilities, for example, that's a hint that you might want to split it up.
Note also that Java specifically introduced the static import: (http://en.wikipedia.org/wiki/Static_import)
Static import is a feature introduced
in the Java programming language that
members (fields and methods) defined
in a class as public static to be used
in Java code without specifying the
class in which the field is defined.
This feature was introduced into the
language in version 5.0.
The feature provides a typesafe
mechanism to include constants into
code without having to reference the
class that originally defined the
field. It also helps to deprecate the
practice of creating a constant
interface: an interface that only
defines constants then writing a class
implementing that interface, which is
considered an inappropriate use of
interfaces[1].
The mechanism can be used to reference
individual members of a class:
import static java.lang.Math.PI;
import static java.lang.Math.pow;
or all the static members of a class:
import static java.lang.Math.*;
While I agree with the sentiment that it sounds like a reasonable solution (as others have already stated), one thing you may want to consider is, from a design standpoint, why do you have a class just for "utility" purposes. Are those functionals truly general across the entire system, or are they really related to some specific class of objects within your architecture.
As long as you have thought about that, I see no problem with your solution.
The Collections class in Java SDK has static members only.
So, there you go, as long as you have proper justification -- its not a bad design
Utility methods are often placed in classes with only static methods (like StringUtils.) Global constants are also placed in their own class so that they can be imported by the rest of the code (public final static attributes.)
Both uses are quite common and have private default constructors to prevent them from being instantiated. Declaring the class final prevents the mistake of trying to override static methods.
If by static member variables you did not mean global constants, you might want to place the methods accessing those variables in a class of their own. In that case, could you eleborate on what those variables do in your code?
This is typically how utility classes are designed and there is nothing wrong about it. Famous examples include o.a.c.l.StringUtils, o.a.c.d.DbUtils, o.s.w.b.ServletRequestUtils, etc.
According to a rigid interpretation of Object Oriented Design, a utility class is something to be avoided.
The problem is that if you follow a rigid interpretation then you would need to force your class into some sort object in order to accomplish many things.
Even the Java designers make utility classes (java.lang.Math comes to mind)
Your options are:
double distance = Math.sqrt(x*x + y*y); //using static utility class
vs:
RootCalculator mySquareRooter = new SquareRootCalculator();
mySquareRooter.setValueToRoot(x*x + y*y);
double distance;
try{
distance = mySquareRooter.getRoot();
}
catch InvalidParameterException ......yadda yadda yadda.
Even if we were to avoid the verbose method, we could still end up with:
Mathemetician myMathD00d = new Mathemetician()
double distance = myMathD00d.sqrt(...);
in this instance, .sqrt() is still static, so what would the point be in creating the object in the first place?
The answer is, create utility classes when your other option would be to create some sort of artificial "Worker" class that has no or little use for instance variables.
This link http://java.dzone.com/articles/why-static-bad-and-how-avoid seems to go against most of the answers here. Even if it contains no member variables (i.e. no state), a static class can still be a bad idea because it cannot be mocked or extended (subclassed), so it is defeating some of the principles of OO
I wouldn't be concerned over a utility class containing static methods.
However, static members are essentially global data and should be avoided. They may be acceptable if they are used for caching results of the static methods and such, but if they are used as "real" data that may lead to all kinds of problems, such as hidden dependencies and difficulties to set up tests.
From TSLint’s docs:
Users who come from a Java-style OO language may wrap their utility functions in an extra class, instead of putting them at the top level.
The best way is to use a constant, like this:
export const Util = {
print (data: string): void {
console.log(data)
}
}
Examples of incorrect code for this rule:
class EmptyClass {}
class ConstructorOnly {
constructor() {
foo();
}
}
// Use an object instead:
class StaticOnly {
static version = 42;
static hello() {
console.log('Hello, world!');
}
}
Examples of correct code for this rule:
class EmptyClass extends SuperClass {}
class ParameterProperties {
constructor(public name: string) {}
}
const StaticOnly = {
version: 42,
hello() {
console.log('Hello, world!');
},
};
I am working on my first Android Project. I have a Service class that waits for receive intents to retrieve some information from a remote server. This service of mine looks something like this:
public class MyService extends IntentService{
public static final String ACTION_INTENT_01 = "xyz.actionIntent01";
public static final String ACTION_INTENT_02 = "xyz.actionIntent02";
public static final String ACTION_INTENT_03 = "xyz.actionIntent03";
... A lot of constant more...
public static final String ACTION_INTENT_01_EXTRA = "xyz.actionIntent01Extra";
...more and more constants...
public MyService(){
...
}
/*The Rest of The Service*/
}
My question is, what is better, having a lot of constant strings inside this class or declare them on the String.xml file and access them by getString(R.string.ACTION_INTENT_03) ??
Thanks!
None of these. I would recommend to have a constants class and put these constants in that class. In this way your service class is smaller and easier to maintain.
You should put strings in strings XML files only if those are subject for localization changes: in English have a specific value, in French a different value and so on. Or if you want to use them in XML UI layouts. So if you have constants to use only in code, there's no reason to have them in XML strings.
You can do in both ways. Personally I declare the strings that are showed in the UI into strings.xml, and string constants in the source code.
One reason the string resources to be declared in the strings.xml is that later they are easy to localize.
Declare them in strings.xml because if you are modifying value that modified will be reflected everywhere.
We have some devs on Android part of our application who actively use prefixing of class member variables with "m*".
What is the origin of "mThis" which is basically:
class SomeClass {
private final SomeClass mThis;
SomeClass() {
mthis = this;
}
}
and this notation in general?
Actually I guess the question is more about the m-prefix, not the goal of having this as your own field.
So regarding the prefix, this is a coding convention used by android team: all member variables (aka fields) are prefixed with "m". That's it, basically. Other android developers might use it because they have browsed through android sources and have deemed it appropriate to use this convention in their own code.
BTW, it's not common in general java programming, I believe common java coding standards usually discourage using any kind of prefixes for anything.
I assume it comes handy when you need to pass a reference to the instance in an inner class, and you don't want to use the "fully qualified" this. i.e SomeClass.this. Nevertheless, it seems redundant to me.
This article suggests it comes from ancient habits peculiar to the Microsoft ecosystem -- however, prefixing members of structs with some shorthand of the struct it is contained in is an old C habit from the days when identifiers, all identifiers (include structure member names), had to be unique in the first eight characters. Prefixing the names with a short-hand version of the name of the containing structure was an easy mechanism to ensure unique names:
struct inode {
int number;
struct device *dev;
}
struct file_descriptor {
int number;
struct inode *i;
}
In this case, number is duplicated, non-unique, and trouble.
Newer versions of C made this a non-issue by placing struct names into their namespaces, but some portion of this habit has carried over: the Linux kernel, for example, is filled with:
struct iattr {
unsigned int ia_valid;
umode_t ia_mode;
uid_t ia_uid;
....
and
struct inode {
/* RCU path lookup touches following: */
umode_t i_mode;
uid_t i_uid;
gid_t i_gid;
const struct inode_operations *i_op;
struct super_block *i_sb;
...
where the leading ia_ and i_ are from the struct iattr and struct inode -- which makes it slightly easier to read chains like this:
if (!IS_ERR(cookie) && path->dentry->d_inode->i_op->put_link)
path->dentry->d_inode->i_op->put_link(path->dentry, nd, cookie);
(Really. fs/namei.c, lines 821 and 822 in my source.)
It avoids accidently using a local variable when you meant to use the member (which the m is short for) variable of the object.
private String name;
private String mName;
public void setName(String name) {
name = name; //wrong, just set the parameter variable to itself
this.name = name; //ok, but has 'this.' which isn't a problem, but some people don't like it
mName = name; //simples
}
m for member variables, s for statics. It's a common naming convention. But like neutrino I don't use it very much. If you use a modern IDE, the syntax color-coding gives you the same information (actually more, because it works whether the original coder followed the naming convention or not).
I use the m prefix to define global variables for the class instance. I don't know why, but when I started and looked over other android code, it was like that.